From e18fcb82cb5d9a14c506d242417fc9bf0a2a73db Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 19 Jul 2024 12:01:26 -0700 Subject: [PATCH] fix!: [google-cloud-discoveryengine] update sample query, sample query set patterns (#12911) - [ ] Regenerate this pull request now. BEGIN_COMMIT_OVERRIDE fix!: [google-cloud-discoveryengine] update sample query, sample query set patterns feat: A new resource pattern value `projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}` added to the resource definition `discoveryengine.googleapis.com/SampleQuery` feat: A new resource pattern value `projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}` added to the resource definition `discoveryengine.googleapis.com/SampleQuerySet` docs: keep the API doc up-to-date with recent changes feat: [google-cloud-discoveryengine] add sample query set APIs feat: add sample query APIs feat: add evaluation APIs feat: [google-cloud-discoveryengine] add Chunk resource in the search response END_COMMIT_OVERRIDE feat: A new resource pattern value `projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}` added to the resource definition `discoveryengine.googleapis.com/SampleQuery` feat: A new resource pattern value `projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}` added to the resource definition `discoveryengine.googleapis.com/SampleQuerySet` docs: keep the API doc up-to-date with recent changes PiperOrigin-RevId: 653290553 Source-Link: https://github.com/googleapis/googleapis/commit/1964be3cc2e5379611c6acb91f7c21a307e44a21 Source-Link: https://github.com/googleapis/googleapis-gen/commit/71a6ec93605bb813500d75da4e99924a2c773a99 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRpc2NvdmVyeWVuZ2luZS8uT3dsQm90LnlhbWwiLCJoIjoiNzFhNmVjOTM2MDViYjgxMzUwMGQ3NWRhNGU5OTkyNGEyYzc3M2E5OSJ9 BEGIN_NESTED_COMMIT feat: [google-cloud-discoveryengine] add sample query set APIs feat: add sample query APIs feat: add evaluation APIs PiperOrigin-RevId: 653246344 Source-Link: https://github.com/googleapis/googleapis/commit/4e570dba2487144e53d008e424013a9e6956c1d8 Source-Link: https://github.com/googleapis/googleapis-gen/commit/18fd0a2b15ab00c7419cdbd446603141ca89f750 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRpc2NvdmVyeWVuZ2luZS8uT3dsQm90LnlhbWwiLCJoIjoiMThmZDBhMmIxNWFiMDBjNzQxOWNkYmQ0NDY2MDMxNDFjYTg5Zjc1MCJ9 END_NESTED_COMMIT BEGIN_NESTED_COMMIT feat: [google-cloud-discoveryengine] add Chunk resource in the search response docs: keep the API doc up-to-date with recent changes PiperOrigin-RevId: 652981596 Source-Link: https://github.com/googleapis/googleapis/commit/f6352d6625dae53d2be00e23cb5d14e22a15154e Source-Link: https://github.com/googleapis/googleapis-gen/commit/5952bc2f8cb53d238764b9a462e7ee5bc07b822e Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRpc2NvdmVyeWVuZ2luZS8uT3dsQm90LnlhbWwiLCJoIjoiNTk1MmJjMmY4Y2I1M2QyMzg3NjRiOWE0NjJlN2VlNWJjMDdiODIyZSJ9 END_NESTED_COMMIT BEGIN_NESTED_COMMIT feat: [google-cloud-discoveryengine] add sample query set APIs feat: add sample query APIs feat: add evaluation APIs PiperOrigin-RevId: 652877459 Source-Link: https://github.com/googleapis/googleapis/commit/afa4805a223f19025af7e23d4288ed19696659b4 Source-Link: https://github.com/googleapis/googleapis-gen/commit/fcac7782b9100c159440291b57608e57eb9b7e0f Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRpc2NvdmVyeWVuZ2luZS8uT3dsQm90LnlhbWwiLCJoIjoiZmNhYzc3ODJiOTEwMGMxNTk0NDAyOTFiNTc2MDhlNTdlYjliN2UwZiJ9 END_NESTED_COMMIT --------- Co-authored-by: Owl Bot Co-authored-by: Victor Chudnovsky --- .../evaluation_service.rst | 10 + .../sample_query_service.rst | 10 + .../sample_query_set_service.rst | 10 + .../discoveryengine_v1alpha/services_.rst | 3 + .../evaluation_service.rst | 10 + .../sample_query_service.rst | 10 + .../sample_query_set_service.rst | 10 + .../docs/discoveryengine_v1beta/services_.rst | 3 + .../google/cloud/discoveryengine/__init__.py | 86 + .../cloud/discoveryengine/gapic_version.py | 2 +- .../cloud/discoveryengine_v1/gapic_version.py | 2 +- .../cloud/discoveryengine_v1alpha/__init__.py | 75 + .../gapic_metadata.json | 282 + .../discoveryengine_v1alpha/gapic_version.py | 2 +- .../services/evaluation_service/__init__.py | 22 + .../evaluation_service/async_client.py | 1002 +++ .../services/evaluation_service/client.py | 1535 ++++ .../services/evaluation_service/pagers.py | 293 + .../evaluation_service/transports/__init__.py | 36 + .../evaluation_service/transports/base.py | 243 + .../evaluation_service/transports/grpc.py | 435 + .../transports/grpc_asyncio.py | 465 ++ .../evaluation_service/transports/rest.py | 1271 +++ .../services/sample_query_service/__init__.py | 22 + .../sample_query_service/async_client.py | 1231 +++ .../services/sample_query_service/client.py | 1659 ++++ .../services/sample_query_service/pagers.py | 162 + .../transports/__init__.py | 38 + .../sample_query_service/transports/base.py | 272 + .../sample_query_service/transports/grpc.py | 496 ++ .../transports/grpc_asyncio.py | 540 ++ .../sample_query_service/transports/rest.py | 1528 ++++ .../sample_query_set_service/__init__.py | 22 + .../sample_query_set_service/async_client.py | 1132 +++ .../sample_query_set_service/client.py | 1555 ++++ .../sample_query_set_service/pagers.py | 162 + .../transports/__init__.py | 41 + .../transports/base.py | 262 + .../transports/grpc.py | 455 ++ .../transports/grpc_asyncio.py | 486 ++ .../transports/rest.py | 1241 +++ .../discoveryengine_v1alpha/types/__init__.py | 57 + .../types/evaluation.py | 337 + .../types/evaluation_service.py | 287 + .../types/import_config.py | 173 +- .../types/sample_query.py | 130 + .../types/sample_query_service.py | 262 + .../types/sample_query_set.py | 77 + .../types/sample_query_set_service.py | 265 + .../cloud/discoveryengine_v1beta/__init__.py | 77 + .../gapic_metadata.json | 282 + .../discoveryengine_v1beta/gapic_version.py | 2 +- .../completion_service/transports/rest.py | 16 + .../control_service/transports/rest.py | 8 + .../transports/rest.py | 8 + .../data_store_service/transports/rest.py | 16 + .../document_service/transports/rest.py | 16 + .../engine_service/transports/rest.py | 16 + .../services/evaluation_service/__init__.py | 22 + .../evaluation_service/async_client.py | 1002 +++ .../services/evaluation_service/client.py | 1535 ++++ .../services/evaluation_service/pagers.py | 293 + .../evaluation_service/transports/__init__.py | 36 + .../evaluation_service/transports/base.py | 243 + .../evaluation_service/transports/grpc.py | 435 + .../transports/grpc_asyncio.py | 465 ++ .../evaluation_service/transports/rest.py | 1271 +++ .../transports/rest.py | 8 + .../project_service/transports/rest.py | 16 + .../services/rank_service/transports/rest.py | 8 + .../recommendation_service/transports/rest.py | 8 + .../services/sample_query_service/__init__.py | 22 + .../sample_query_service/async_client.py | 1231 +++ .../services/sample_query_service/client.py | 1659 ++++ .../services/sample_query_service/pagers.py | 159 + .../transports/__init__.py | 38 + .../sample_query_service/transports/base.py | 272 + .../sample_query_service/transports/grpc.py | 496 ++ .../transports/grpc_asyncio.py | 540 ++ .../sample_query_service/transports/rest.py | 1528 ++++ .../sample_query_set_service/__init__.py | 22 + .../sample_query_set_service/async_client.py | 1130 +++ .../sample_query_set_service/client.py | 1553 ++++ .../sample_query_set_service/pagers.py | 162 + .../transports/__init__.py | 41 + .../transports/base.py | 262 + .../transports/grpc.py | 455 ++ .../transports/grpc_asyncio.py | 486 ++ .../transports/rest.py | 1241 +++ .../schema_service/transports/rest.py | 16 + .../services/search_service/async_client.py | 2 + .../services/search_service/client.py | 28 + .../search_service/transports/rest.py | 8 + .../search_tuning_service/transports/rest.py | 16 + .../serving_config_service/transports/rest.py | 8 + .../transports/rest.py | 16 + .../user_event_service/transports/rest.py | 16 + .../discoveryengine_v1beta/types/__init__.py | 59 + .../discoveryengine_v1beta/types/chunk.py | 190 + .../types/conversational_search_service.py | 13 +- .../discoveryengine_v1beta/types/document.py | 2 +- .../types/document_processing_config.py | 71 +- .../types/evaluation.py | 337 + .../types/evaluation_service.py | 287 + .../types/import_config.py | 173 +- .../types/sample_query.py | 130 + .../types/sample_query_service.py | 262 + .../types/sample_query_set.py | 77 + .../types/sample_query_set_service.py | 265 + .../types/search_service.py | 129 +- .../types/serving_config.py | 32 +- ...luation_service_create_evaluation_async.py | 61 + ...aluation_service_create_evaluation_sync.py | 61 + ...evaluation_service_get_evaluation_async.py | 52 + ..._evaluation_service_get_evaluation_sync.py | 52 + ...n_service_list_evaluation_results_async.py | 53 + ...on_service_list_evaluation_results_sync.py | 53 + ...aluation_service_list_evaluations_async.py | 53 + ...valuation_service_list_evaluations_sync.py | 53 + ...query_service_create_sample_query_async.py | 57 + ..._query_service_create_sample_query_sync.py | 57 + ...query_service_delete_sample_query_async.py | 50 + ..._query_service_delete_sample_query_sync.py | 50 + ...le_query_service_get_sample_query_async.py | 52 + ...ple_query_service_get_sample_query_sync.py | 52 + ...ery_service_import_sample_queries_async.py | 60 + ...uery_service_import_sample_queries_sync.py | 60 + ...query_service_list_sample_queries_async.py | 53 + ..._query_service_list_sample_queries_sync.py | 53 + ...query_service_update_sample_query_async.py | 55 + ..._query_service_update_sample_query_sync.py | 55 + ...t_service_create_sample_query_set_async.py | 57 + ...et_service_create_sample_query_set_sync.py | 57 + ...t_service_delete_sample_query_set_async.py | 50 + ...et_service_delete_sample_query_set_sync.py | 50 + ..._set_service_get_sample_query_set_async.py | 52 + ...y_set_service_get_sample_query_set_sync.py | 52 + ...et_service_list_sample_query_sets_async.py | 53 + ...set_service_list_sample_query_sets_sync.py | 53 + ...t_service_update_sample_query_set_async.py | 55 + ...et_service_update_sample_query_set_sync.py | 55 + ...luation_service_create_evaluation_async.py | 61 + ...aluation_service_create_evaluation_sync.py | 61 + ...evaluation_service_get_evaluation_async.py | 52 + ..._evaluation_service_get_evaluation_sync.py | 52 + ...n_service_list_evaluation_results_async.py | 53 + ...on_service_list_evaluation_results_sync.py | 53 + ...aluation_service_list_evaluations_async.py | 53 + ...valuation_service_list_evaluations_sync.py | 53 + ...query_service_create_sample_query_async.py | 57 + ..._query_service_create_sample_query_sync.py | 57 + ...query_service_delete_sample_query_async.py | 50 + ..._query_service_delete_sample_query_sync.py | 50 + ...le_query_service_get_sample_query_async.py | 52 + ...ple_query_service_get_sample_query_sync.py | 52 + ...ery_service_import_sample_queries_async.py | 60 + ...uery_service_import_sample_queries_sync.py | 60 + ...query_service_list_sample_queries_async.py | 53 + ..._query_service_list_sample_queries_sync.py | 53 + ...query_service_update_sample_query_async.py | 55 + ..._query_service_update_sample_query_sync.py | 55 + ...t_service_create_sample_query_set_async.py | 57 + ...et_service_create_sample_query_set_sync.py | 57 + ...t_service_delete_sample_query_set_async.py | 50 + ...et_service_delete_sample_query_set_sync.py | 50 + ..._set_service_get_sample_query_set_async.py | 52 + ...y_set_service_get_sample_query_set_sync.py | 52 + ...et_service_list_sample_query_sets_async.py | 53 + ...set_service_list_sample_query_sets_sync.py | 53 + ...t_service_update_sample_query_set_async.py | 55 + ...et_service_update_sample_query_set_sync.py | 55 + ...adata_google.cloud.discoveryengine.v1.json | 2 +- ..._google.cloud.discoveryengine.v1alpha.json | 2951 ++++++- ...a_google.cloud.discoveryengine.v1beta.json | 2761 ++++++- .../fixup_discoveryengine_v1alpha_keywords.py | 15 + .../fixup_discoveryengine_v1beta_keywords.py | 15 + .../test_evaluation_service.py | 6326 +++++++++++++++ .../test_sample_query_service.py | 7204 +++++++++++++++++ .../test_sample_query_set_service.py | 6631 +++++++++++++++ .../test_data_store_service.py | 14 + .../test_evaluation_service.py | 6322 +++++++++++++++ .../test_sample_query_service.py | 7204 +++++++++++++++++ .../test_sample_query_set_service.py | 6631 +++++++++++++++ .../test_search_service.py | 37 + .../test_serving_config_service.py | 2 + 185 files changed, 86844 insertions(+), 449 deletions(-) create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/evaluation_service.rst create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_service.rst create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_set_service.rst create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/evaluation_service.rst create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_service.rst create mode 100644 packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_set_service.rst create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation_service.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_service.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set_service.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/async_client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/client.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/pagers.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/__init__.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/base.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/chunk.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation_service.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_service.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set.py create mode 100644 packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py create mode 100644 packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_service.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_set_service.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_service.py create mode 100644 packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_set_service.py diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/evaluation_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/evaluation_service.rst new file mode 100644 index 000000000000..e920ed27ff11 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/evaluation_service.rst @@ -0,0 +1,10 @@ +EvaluationService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.evaluation_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_service.rst new file mode 100644 index 000000000000..3325be0e29d2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_service.rst @@ -0,0 +1,10 @@ +SampleQueryService +------------------------------------ + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.sample_query_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.sample_query_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_set_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_set_service.rst new file mode 100644 index 000000000000..67a917dd5ce6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/sample_query_set_service.rst @@ -0,0 +1,10 @@ +SampleQuerySetService +--------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.sample_query_set_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst index eb7b1c46f036..25a46d9759d2 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst @@ -12,10 +12,13 @@ Services for Google Cloud Discoveryengine v1alpha API document_service engine_service estimate_billing_service + evaluation_service grounded_generation_service project_service rank_service recommendation_service + sample_query_service + sample_query_set_service schema_service search_service search_tuning_service diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/evaluation_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/evaluation_service.rst new file mode 100644 index 000000000000..8b76326e63cb --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/evaluation_service.rst @@ -0,0 +1,10 @@ +EvaluationService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.evaluation_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.evaluation_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_service.rst new file mode 100644 index 000000000000..87a0f78179a4 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_service.rst @@ -0,0 +1,10 @@ +SampleQueryService +------------------------------------ + +.. automodule:: google.cloud.discoveryengine_v1beta.services.sample_query_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_set_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_set_service.rst new file mode 100644 index 000000000000..e7636d89c4fc --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/sample_query_set_service.rst @@ -0,0 +1,10 @@ +SampleQuerySetService +--------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.sample_query_set_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/services_.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/services_.rst index 216a1c4e58c6..a1960515a76d 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/services_.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1beta/services_.rst @@ -9,10 +9,13 @@ Services for Google Cloud Discoveryengine v1beta API data_store_service document_service engine_service + evaluation_service grounded_generation_service project_service rank_service recommendation_service + sample_query_service + sample_query_set_service schema_service search_service search_tuning_service diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py index 0687094e6a64..e5924a283909 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py @@ -54,6 +54,12 @@ from google.cloud.discoveryengine_v1beta.services.engine_service.client import ( EngineServiceClient, ) +from google.cloud.discoveryengine_v1beta.services.evaluation_service.async_client import ( + EvaluationServiceAsyncClient, +) +from google.cloud.discoveryengine_v1beta.services.evaluation_service.client import ( + EvaluationServiceClient, +) from google.cloud.discoveryengine_v1beta.services.grounded_generation_service.async_client import ( GroundedGenerationServiceAsyncClient, ) @@ -78,6 +84,18 @@ from google.cloud.discoveryengine_v1beta.services.recommendation_service.client import ( RecommendationServiceClient, ) +from google.cloud.discoveryengine_v1beta.services.sample_query_service.async_client import ( + SampleQueryServiceAsyncClient, +) +from google.cloud.discoveryengine_v1beta.services.sample_query_service.client import ( + SampleQueryServiceClient, +) +from google.cloud.discoveryengine_v1beta.services.sample_query_set_service.async_client import ( + SampleQuerySetServiceAsyncClient, +) +from google.cloud.discoveryengine_v1beta.services.sample_query_set_service.client import ( + SampleQuerySetServiceClient, +) from google.cloud.discoveryengine_v1beta.services.schema_service.async_client import ( SchemaServiceAsyncClient, ) @@ -115,6 +133,7 @@ UserEventServiceClient, ) from google.cloud.discoveryengine_v1beta.types.answer import Answer +from google.cloud.discoveryengine_v1beta.types.chunk import Chunk from google.cloud.discoveryengine_v1beta.types.common import ( CustomAttribute, DoubleList, @@ -209,6 +228,19 @@ TuneEngineResponse, UpdateEngineRequest, ) +from google.cloud.discoveryengine_v1beta.types.evaluation import ( + Evaluation, + QualityMetrics, +) +from google.cloud.discoveryengine_v1beta.types.evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) from google.cloud.discoveryengine_v1beta.types.grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, @@ -227,6 +259,9 @@ ImportDocumentsRequest, ImportDocumentsResponse, ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, ImportSuggestionDenyListEntriesMetadata, ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, @@ -257,6 +292,24 @@ RecommendRequest, RecommendResponse, ) +from google.cloud.discoveryengine_v1beta.types.sample_query import SampleQuery +from google.cloud.discoveryengine_v1beta.types.sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from google.cloud.discoveryengine_v1beta.types.sample_query_set import SampleQuerySet +from google.cloud.discoveryengine_v1beta.types.sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) from google.cloud.discoveryengine_v1beta.types.schema import Schema from google.cloud.discoveryengine_v1beta.types.schema_service import ( CreateSchemaMetadata, @@ -350,6 +403,8 @@ "DocumentServiceAsyncClient", "EngineServiceClient", "EngineServiceAsyncClient", + "EvaluationServiceClient", + "EvaluationServiceAsyncClient", "GroundedGenerationServiceClient", "GroundedGenerationServiceAsyncClient", "ProjectServiceClient", @@ -358,6 +413,10 @@ "RankServiceAsyncClient", "RecommendationServiceClient", "RecommendationServiceAsyncClient", + "SampleQueryServiceClient", + "SampleQueryServiceAsyncClient", + "SampleQuerySetServiceClient", + "SampleQuerySetServiceAsyncClient", "SchemaServiceClient", "SchemaServiceAsyncClient", "SearchServiceClient", @@ -371,6 +430,7 @@ "UserEventServiceClient", "UserEventServiceAsyncClient", "Answer", + "Chunk", "CustomAttribute", "DoubleList", "EmbeddingConfig", @@ -446,6 +506,15 @@ "TuneEngineRequest", "TuneEngineResponse", "UpdateEngineRequest", + "Evaluation", + "QualityMetrics", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "GetEvaluationRequest", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", @@ -462,6 +531,9 @@ "ImportDocumentsRequest", "ImportDocumentsResponse", "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", "ImportSuggestionDenyListEntriesMetadata", "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", @@ -483,6 +555,20 @@ "RankResponse", "RecommendRequest", "RecommendResponse", + "SampleQuery", + "CreateSampleQueryRequest", + "DeleteSampleQueryRequest", + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "UpdateSampleQueryRequest", + "SampleQuerySet", + "CreateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "UpdateSampleQuerySetRequest", "Schema", "CreateSchemaMetadata", "CreateSchemaRequest", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py index 9d5fd39a4c03..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.14" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py index 9d5fd39a4c03..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.14" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} 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 7661bdba4177..4cc17d87193a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py @@ -42,6 +42,10 @@ EstimateBillingServiceAsyncClient, EstimateBillingServiceClient, ) +from .services.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, +) from .services.grounded_generation_service import ( GroundedGenerationServiceAsyncClient, GroundedGenerationServiceClient, @@ -52,6 +56,14 @@ RecommendationServiceAsyncClient, RecommendationServiceClient, ) +from .services.sample_query_service import ( + SampleQueryServiceAsyncClient, + SampleQueryServiceClient, +) +from .services.sample_query_set_service import ( + SampleQuerySetServiceAsyncClient, + SampleQuerySetServiceClient, +) from .services.schema_service import SchemaServiceAsyncClient, SchemaServiceClient from .services.search_service import SearchServiceAsyncClient, SearchServiceClient from .services.search_tuning_service import ( @@ -174,6 +186,16 @@ EstimateDataSizeRequest, EstimateDataSizeResponse, ) +from .types.evaluation import Evaluation, QualityMetrics +from .types.evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) from .types.grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, @@ -192,6 +214,9 @@ ImportDocumentsRequest, ImportDocumentsResponse, ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, ImportSuggestionDenyListEntriesMetadata, ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, @@ -221,6 +246,24 @@ ) from .types.rank_service import RankingRecord, RankRequest, RankResponse from .types.recommendation_service import RecommendRequest, RecommendResponse +from .types.sample_query import SampleQuery +from .types.sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from .types.sample_query_set import SampleQuerySet +from .types.sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) from .types.schema import FieldConfig, Schema from .types.schema_service import ( CreateSchemaMetadata, @@ -301,10 +344,13 @@ "DocumentServiceAsyncClient", "EngineServiceAsyncClient", "EstimateBillingServiceAsyncClient", + "EvaluationServiceAsyncClient", "GroundedGenerationServiceAsyncClient", "ProjectServiceAsyncClient", "RankServiceAsyncClient", "RecommendationServiceAsyncClient", + "SampleQueryServiceAsyncClient", + "SampleQuerySetServiceAsyncClient", "SchemaServiceAsyncClient", "SearchServiceAsyncClient", "SearchTuningServiceAsyncClient", @@ -352,6 +398,10 @@ "CreateDocumentRequest", "CreateEngineMetadata", "CreateEngineRequest", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "CreateSampleQueryRequest", + "CreateSampleQuerySetRequest", "CreateSchemaMetadata", "CreateSchemaRequest", "CreateSessionRequest", @@ -369,6 +419,8 @@ "DeleteDocumentRequest", "DeleteEngineMetadata", "DeleteEngineRequest", + "DeleteSampleQueryRequest", + "DeleteSampleQuerySetRequest", "DeleteSchemaMetadata", "DeleteSchemaRequest", "DeleteSessionRequest", @@ -392,6 +444,8 @@ "EstimateDataSizeMetadata", "EstimateDataSizeRequest", "EstimateDataSizeResponse", + "Evaluation", + "EvaluationServiceClient", "FactChunk", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", @@ -408,8 +462,11 @@ "GetDocumentProcessingConfigRequest", "GetDocumentRequest", "GetEngineRequest", + "GetEvaluationRequest", "GetProcessedDocumentRequest", "GetProjectRequest", + "GetSampleQueryRequest", + "GetSampleQuerySetRequest", "GetSchemaRequest", "GetServingConfigRequest", "GetSessionRequest", @@ -423,6 +480,9 @@ "ImportDocumentsRequest", "ImportDocumentsResponse", "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", "ImportSuggestionDenyListEntriesMetadata", "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", @@ -445,6 +505,14 @@ "ListDocumentsResponse", "ListEnginesRequest", "ListEnginesResponse", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", "ListSchemasRequest", "ListSchemasResponse", "ListServingConfigsRequest", @@ -473,6 +541,7 @@ "PurgeUserEventsMetadata", "PurgeUserEventsRequest", "PurgeUserEventsResponse", + "QualityMetrics", "Query", "RankRequest", "RankResponse", @@ -487,6 +556,10 @@ "Reply", "ReportConsentChangeRequest", "ResumeEngineRequest", + "SampleQuery", + "SampleQueryServiceClient", + "SampleQuerySet", + "SampleQuerySetServiceClient", "Schema", "SchemaServiceClient", "SearchAddOn", @@ -522,6 +595,8 @@ "UpdateDocumentProcessingConfigRequest", "UpdateDocumentRequest", "UpdateEngineRequest", + "UpdateSampleQueryRequest", + "UpdateSampleQuerySetRequest", "UpdateSchemaMetadata", "UpdateSchemaRequest", "UpdateServingConfigRequest", 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 afe98968cc12..fd770a37dd08 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 @@ -911,6 +911,85 @@ } } }, + "EvaluationService": { + "clients": { + "grpc": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EvaluationServiceAsyncClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + }, + "rest": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + } + } + }, "GroundedGenerationService": { "clients": { "grpc": { @@ -1077,6 +1156,209 @@ } } }, + "SampleQueryService": { + "clients": { + "grpc": { + "libraryClient": "SampleQueryServiceClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SampleQueryServiceAsyncClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + }, + "rest": { + "libraryClient": "SampleQueryServiceClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + } + } + }, + "SampleQuerySetService": { + "clients": { + "grpc": { + "libraryClient": "SampleQuerySetServiceClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SampleQuerySetServiceAsyncClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + }, + "rest": { + "libraryClient": "SampleQuerySetServiceClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + } + } + }, "SchemaService": { "clients": { "grpc": { diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py index 9d5fd39a4c03..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.14" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/__init__.py new file mode 100644 index 000000000000..a84af6a63a20 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import EvaluationServiceAsyncClient +from .client import EvaluationServiceClient + +__all__ = ( + "EvaluationServiceClient", + "EvaluationServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py new file mode 100644 index 000000000000..b88d447231f2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py @@ -0,0 +1,1002 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.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 timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.evaluation_service import pagers +from google.cloud.discoveryengine_v1alpha.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1alpha.types import evaluation +from google.cloud.discoveryengine_v1alpha.types import evaluation_service + +from .client import EvaluationServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport + + +class EvaluationServiceAsyncClient: + """Service for managing + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s, + """ + + _client: EvaluationServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EvaluationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EvaluationServiceClient._DEFAULT_UNIVERSE + + branch_path = staticmethod(EvaluationServiceClient.branch_path) + parse_branch_path = staticmethod(EvaluationServiceClient.parse_branch_path) + data_store_path = staticmethod(EvaluationServiceClient.data_store_path) + parse_data_store_path = staticmethod(EvaluationServiceClient.parse_data_store_path) + evaluation_path = staticmethod(EvaluationServiceClient.evaluation_path) + parse_evaluation_path = staticmethod(EvaluationServiceClient.parse_evaluation_path) + location_path = staticmethod(EvaluationServiceClient.location_path) + parse_location_path = staticmethod(EvaluationServiceClient.parse_location_path) + sample_query_path = staticmethod(EvaluationServiceClient.sample_query_path) + parse_sample_query_path = staticmethod( + EvaluationServiceClient.parse_sample_query_path + ) + sample_query_set_path = staticmethod(EvaluationServiceClient.sample_query_set_path) + parse_sample_query_set_path = staticmethod( + EvaluationServiceClient.parse_sample_query_set_path + ) + serving_config_path = staticmethod(EvaluationServiceClient.serving_config_path) + parse_serving_config_path = staticmethod( + EvaluationServiceClient.parse_serving_config_path + ) + common_billing_account_path = staticmethod( + EvaluationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EvaluationServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(EvaluationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + EvaluationServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + EvaluationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + EvaluationServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(EvaluationServiceClient.common_project_path) + parse_common_project_path = staticmethod( + EvaluationServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(EvaluationServiceClient.common_location_path) + parse_common_location_path = staticmethod( + EvaluationServiceClient.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: + EvaluationServiceAsyncClient: The constructed client. + """ + return EvaluationServiceClient.from_service_account_info.__func__(EvaluationServiceAsyncClient, 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: + EvaluationServiceAsyncClient: The constructed client. + """ + return EvaluationServiceClient.from_service_account_file.__func__(EvaluationServiceAsyncClient, 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 EvaluationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(EvaluationServiceClient).get_transport_class, type(EvaluationServiceClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EvaluationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation] + method. + name (:class:`str`): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, 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.ListEvaluationsAsyncPager: + r"""Gets a list of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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_evaluations(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListEvaluationsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + parent (:class:`str`): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s + under this location, regardless of whether or not this + location 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationsAsyncPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcd_evaluation.Evaluation] = 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 + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1alpha.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1alpha.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(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.CreateEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (:class:`google.cloud.discoveryengine_v1alpha.types.Evaluation`): + Required. The + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + to create. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.Evaluation` An evaluation is a single execution (or run) of an evaluation process. It + encapsulates the state of the evaluation and the + resulting 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, evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_evaluation.Evaluation, + metadata_type=evaluation_service.CreateEvaluationMetadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + evaluation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationResultsAsyncPager: + r"""Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation_results(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + evaluation (:class:`str`): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless + of whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + 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([evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_results + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation", request.evaluation),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationResultsAsyncPager( + 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "EvaluationServiceAsyncClient": + 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__ = ("EvaluationServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py new file mode 100644 index 000000000000..086f5e2747c6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py @@ -0,0 +1,1535 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.evaluation_service import pagers +from google.cloud.discoveryengine_v1alpha.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1alpha.types import evaluation +from google.cloud.discoveryengine_v1alpha.types import evaluation_service + +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc import EvaluationServiceGrpcTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .transports.rest import EvaluationServiceRestTransport + + +class EvaluationServiceClientMeta(type): + """Metaclass for the EvaluationService 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[EvaluationServiceTransport]] + _transport_registry["grpc"] = EvaluationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EvaluationServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EvaluationServiceTransport]: + """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 EvaluationServiceClient(metaclass=EvaluationServiceClientMeta): + """Service for managing + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceClient: 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: + EvaluationServiceClient: 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) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: 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 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 evaluation_path( + project: str, + location: str, + evaluation: str, + ) -> str: + """Returns a fully-qualified evaluation string.""" + return ( + "projects/{project}/locations/{location}/evaluations/{evaluation}".format( + project=project, + location=location, + evaluation=evaluation, + ) + ) + + @staticmethod + def parse_evaluation_path(path: str) -> Dict[str, str]: + """Parses a evaluation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/evaluations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def 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_location_path(path: str) -> Dict[str, str]: + """Parses a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_path( + project: str, + location: str, + sample_query_set: str, + sample_query: str, + ) -> str: + """Returns a fully-qualified sample_query string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + + @staticmethod + def parse_sample_query_path(path: str) -> Dict[str, str]: + """Parses a sample_query path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)/sampleQueries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?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 + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = EvaluationServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or EvaluationServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = EvaluationServiceClient._read_environment_variables() + self._client_cert_source = EvaluationServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = EvaluationServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, EvaluationServiceTransport) + if transport_provided: + # transport is a EvaluationServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(EvaluationServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or EvaluationServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[EvaluationServiceTransport], + Callable[..., EvaluationServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EvaluationServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation] + method. + name (str): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + 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.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, 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.ListEvaluationsPager: + r"""Gets a list of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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_evaluations(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListEvaluationsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s + under this location, regardless of whether or not this + location 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.evaluation_service.pagers.ListEvaluationsPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(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_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcd_evaluation.Evaluation] = 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 + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1alpha.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1alpha.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (google.cloud.discoveryengine_v1alpha.types.Evaluation): + Required. The + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + to create. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.Evaluation` An evaluation is a single execution (or run) of an evaluation process. It + encapsulates the state of the evaluation and the + resulting 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, evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_evaluation.Evaluation, + metadata_type=evaluation_service.CreateEvaluationMetadata, + ) + + # Done; return the response. + return response + + def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + evaluation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationResultsPager: + r"""Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_evaluation_results(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + evaluation (str): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless + of whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.evaluation_service.pagers.ListEvaluationResultsPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + 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([evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation", request.evaluation),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EvaluationServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("EvaluationServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/pagers.py new file mode 100644 index 000000000000..189ad6afc888 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/pagers.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1alpha.types import evaluation, evaluation_service + + +class ListEvaluationsPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse` + 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[..., evaluation_service.ListEvaluationsResponse], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + 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.ListEvaluationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse): + 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 = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationsResponse]: + 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[evaluation.Evaluation]: + for page in self.pages: + yield from page.evaluations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationsAsyncPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse` + 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[evaluation_service.ListEvaluationsResponse]], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + 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.ListEvaluationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEvaluationsResponse): + 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 = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[evaluation_service.ListEvaluationsResponse]: + 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[evaluation.Evaluation]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse` + 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[..., evaluation_service.ListEvaluationResultsResponse], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + 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.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse): + 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 = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationResultsResponse]: + 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[evaluation_service.ListEvaluationResultsResponse.EvaluationResult]: + for page in self.pages: + yield from page.evaluation_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsAsyncPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse` + 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[evaluation_service.ListEvaluationResultsResponse] + ], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + 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.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse): + 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 = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationResultsResponse]: + 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[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/__init__.py new file mode 100644 index 000000000000..992af2ba4c25 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport +from .grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .rest import EvaluationServiceRestInterceptor, EvaluationServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EvaluationServiceTransport]] +_transport_registry["grpc"] = EvaluationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EvaluationServiceRestTransport + +__all__ = ( + "EvaluationServiceTransport", + "EvaluationServiceGrpcTransport", + "EvaluationServiceGrpcAsyncIOTransport", + "EvaluationServiceRestTransport", + "EvaluationServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/base.py new file mode 100644 index 000000000000..0464fbba9c86 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/base.py @@ -0,0 +1,243 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from google.cloud.discoveryengine_v1alpha.types import evaluation, evaluation_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class EvaluationServiceTransport(abc.ABC): + """Abstract transport class for EvaluationService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_evaluation: gapic_v1.method.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: gapic_v1.method.wrap_method( + self.create_evaluation, + default_timeout=300.0, + client_info=client_info, + ), + self.list_evaluation_results: gapic_v1.method.wrap_method( + self.list_evaluation_results, + 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_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], + Union[evaluation.Evaluation, Awaitable[evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Union[ + evaluation_service.ListEvaluationsResponse, + Awaitable[evaluation_service.ListEvaluationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Union[ + evaluation_service.ListEvaluationResultsResponse, + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("EvaluationServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc.py new file mode 100644 index 000000000000..f6b854277e4a --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc.py @@ -0,0 +1,435 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport + + +class EvaluationServiceGrpcTransport(EvaluationServiceTransport): + """gRPC backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Returns: + Callable[[~.GetEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Gets a list of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s. + + Returns: + Callable[[~.ListEvaluationsRequest], + ~.ListEvaluationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + Returns: + Callable[[~.CreateEvaluationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_evaluation"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + ~.ListEvaluationResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("EvaluationServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..702de8607980 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/grpc_asyncio.py @@ -0,0 +1,465 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport + + +class EvaluationServiceGrpcAsyncIOTransport(EvaluationServiceTransport): + """gRPC AsyncIO backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._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_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], Awaitable[evaluation.Evaluation] + ]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Returns: + Callable[[~.GetEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Awaitable[evaluation_service.ListEvaluationsResponse], + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Gets a list of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s. + + Returns: + Callable[[~.ListEvaluationsRequest], + Awaitable[~.ListEvaluationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + Returns: + Callable[[~.CreateEvaluationRequest], + 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_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_evaluation"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + Awaitable[~.ListEvaluationResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_evaluation: gapic_v1.method_async.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method_async.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: gapic_v1.method_async.wrap_method( + self.create_evaluation, + default_timeout=300.0, + client_info=client_info, + ), + self.list_evaluation_results: gapic_v1.method_async.wrap_method( + self.list_evaluation_results, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("EvaluationServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py new file mode 100644 index 000000000000..753bfe047b59 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py @@ -0,0 +1,1271 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import 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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import EvaluationServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class EvaluationServiceRestInterceptor: + """Interceptor for EvaluationService. + + 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 EvaluationServiceRestTransport. + + .. code-block:: python + class MyCustomEvaluationServiceInterceptor(EvaluationServiceRestInterceptor): + def pre_create_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_results(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_results(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EvaluationServiceRestTransport(interceptor=MyCustomEvaluationServiceInterceptor()) + client = EvaluationServiceClient(transport=transport) + + + """ + + def pre_create_evaluation( + self, + request: evaluation_service.CreateEvaluationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.CreateEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_evaluation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_evaluation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_get_evaluation( + self, + request: evaluation_service.GetEvaluationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation( + self, response: evaluation.Evaluation + ) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_evaluation_results( + self, + request: evaluation_service.ListEvaluationResultsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + evaluation_service.ListEvaluationResultsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_evaluation_results + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_results( + self, response: evaluation_service.ListEvaluationResultsResponse + ) -> evaluation_service.ListEvaluationResultsResponse: + """Post-rpc interceptor for list_evaluation_results + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_evaluations( + self, + request: evaluation_service.ListEvaluationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluations( + self, response: evaluation_service.ListEvaluationsResponse + ) -> evaluation_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService 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 EvaluationService 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 EvaluationService 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 EvaluationService 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 EvaluationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EvaluationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EvaluationServiceRestInterceptor + + +class EvaluationServiceRestTransport(EvaluationServiceTransport): + """REST backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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[EvaluationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 EvaluationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataConnector/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/*/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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataConnector}/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/*/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 _CreateEvaluation(EvaluationServiceRestStub): + def __hash__(self): + return hash("CreateEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.CreateEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create evaluation method over HTTP. + + Args: + request (~.evaluation_service.CreateEvaluationRequest): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The 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/*}/evaluations", + "body": "evaluation", + }, + ] + request, metadata = self._interceptor.pre_create_evaluation( + request, metadata + ) + pb_request = evaluation_service.CreateEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_evaluation(resp) + return resp + + class _GetEvaluation(EvaluationServiceRestStub): + def __hash__(self): + return hash("GetEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.GetEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationRequest): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting data. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + pb_request = evaluation_service.GetEvaluationRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_evaluation(resp) + return resp + + class _ListEvaluationResults(EvaluationServiceRestStub): + def __hash__(self): + return hash("ListEvaluationResults") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.ListEvaluationResultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_service.ListEvaluationResultsResponse: + r"""Call the list evaluation results method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationResultsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation_service.ListEvaluationResultsResponse: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{evaluation=projects/*/locations/*/evaluations/*}:listResults", + }, + ] + request, metadata = self._interceptor.pre_list_evaluation_results( + request, metadata + ) + pb_request = evaluation_service.ListEvaluationResultsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation_service.ListEvaluationResultsResponse() + pb_resp = evaluation_service.ListEvaluationResultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluation_results(resp) + return resp + + class _ListEvaluations(EvaluationServiceRestStub): + def __hash__(self): + return hash("ListEvaluations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.ListEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationsRequest): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation_service.ListEvaluationsResponse: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}/evaluations", + }, + ] + request, metadata = self._interceptor.pre_list_evaluations( + request, metadata + ) + pb_request = evaluation_service.ListEvaluationsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation_service.ListEvaluationsResponse() + pb_resp = evaluation_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluations(resp) + return resp + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], 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._CreateEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationResults(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(EvaluationServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(EvaluationServiceRestStub): + 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/*/dataConnector/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/*/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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/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(EvaluationServiceRestStub): + 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/*/dataConnector}/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/*/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__ = ("EvaluationServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/__init__.py new file mode 100644 index 000000000000..41a401cc78de --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SampleQueryServiceAsyncClient +from .client import SampleQueryServiceClient + +__all__ = ( + "SampleQueryServiceClient", + "SampleQueryServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/async_client.py new file mode 100644 index 000000000000..635cce437ea8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/async_client.py @@ -0,0 +1,1231 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.sample_query_service import pagers +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +from .client import SampleQueryServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .transports.grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport + + +class SampleQueryServiceAsyncClient: + """Service for managing + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s, + """ + + _client: SampleQueryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SampleQueryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SampleQueryServiceClient._DEFAULT_UNIVERSE + + sample_query_path = staticmethod(SampleQueryServiceClient.sample_query_path) + parse_sample_query_path = staticmethod( + SampleQueryServiceClient.parse_sample_query_path + ) + sample_query_set_path = staticmethod(SampleQueryServiceClient.sample_query_set_path) + parse_sample_query_set_path = staticmethod( + SampleQueryServiceClient.parse_sample_query_set_path + ) + common_billing_account_path = staticmethod( + SampleQueryServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SampleQueryServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SampleQueryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SampleQueryServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SampleQueryServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SampleQueryServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SampleQueryServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SampleQueryServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SampleQueryServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SampleQueryServiceClient.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: + SampleQueryServiceAsyncClient: The constructed client. + """ + return SampleQueryServiceClient.from_service_account_info.__func__(SampleQueryServiceAsyncClient, 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: + SampleQueryServiceAsyncClient: The constructed client. + """ + return SampleQueryServiceClient.from_service_account_file.__func__(SampleQueryServiceAsyncClient, 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 SampleQueryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SampleQueryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQueryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(SampleQueryServiceClient).get_transport_class, + type(SampleQueryServiceClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQueryServiceTransport, + Callable[..., SampleQueryServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQueryServiceTransport,Callable[..., SampleQueryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQueryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SampleQueryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_sample_query( + self, + request: Optional[ + Union[sample_query_service.GetSampleQueryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Gets a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.GetSampleQueryRequest): + request = sample_query_service.GetSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sample_queries( + self, + request: Optional[ + Union[sample_query_service.ListSampleQueriesRequest, 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.ListSampleQueriesAsyncPager: + r"""Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesRequest, dict]]): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + parent (:class:`str`): + Required. The parent sample query set resource name, + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + under this sample query set, regardless of whether or + not this sample query set 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.sample_query_service.pagers.ListSampleQueriesAsyncPager: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.ListSampleQueriesRequest): + request = sample_query_service.ListSampleQueriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sample_queries + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSampleQueriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sample_query( + self, + request: Optional[ + Union[sample_query_service.CreateSampleQueryRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query: Optional[gcd_sample_query.SampleQuery] = None, + sample_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Creates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = await client.create_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query (:class:`google.cloud.discoveryengine_v1alpha.types.SampleQuery`): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + to create. + + This corresponds to the ``sample_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_id (:class:`str`): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1alpha.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQueryRequest.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 ``sample_query_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query, sample_query_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.CreateSampleQueryRequest): + request = sample_query_service.CreateSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query is not None: + request.sample_query = sample_query + if sample_query_id is not None: + request.sample_query_id = sample_query_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_sample_query( + self, + request: Optional[ + Union[sample_query_service.UpdateSampleQueryRequest, dict] + ] = None, + *, + sample_query: Optional[gcd_sample_query.SampleQuery] = 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_sample_query.SampleQuery: + r"""Updates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = await client.update_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery] + method. + sample_query (:class:`google.cloud.discoveryengine_v1alpha.types.SampleQuery`): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query`` 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 imported 'simple query' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.UpdateSampleQueryRequest): + request = sample_query_service.UpdateSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query is not None: + request.sample_query = sample_query + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query.name", request.sample_query.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sample_query( + self, + request: Optional[ + Union[sample_query_service.DeleteSampleQueryRequest, dict] + ] = 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 + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.DeleteSampleQueryRequest): + request = sample_query_service.DeleteSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_sample_queries( + self, + request: Optional[Union[import_config.ImportSampleQueriesRequest, 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 + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + to be successfully imported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(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.ImportSampleQueriesRequest, dict]]): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + 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.ImportSampleQueriesResponse` Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportSampleQueriesRequest): + request = import_config.ImportSampleQueriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_sample_queries + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportSampleQueriesResponse, + metadata_type=import_config.ImportSampleQueriesMetadata, + ) + + # 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SampleQueryServiceAsyncClient": + 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__ = ("SampleQueryServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/client.py new file mode 100644 index 000000000000..585103bf545d --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/client.py @@ -0,0 +1,1659 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 google.cloud.discoveryengine_v1alpha.services.sample_query_service import pagers +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +from .transports.base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .transports.grpc import SampleQueryServiceGrpcTransport +from .transports.grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport +from .transports.rest import SampleQueryServiceRestTransport + + +class SampleQueryServiceClientMeta(type): + """Metaclass for the SampleQueryService 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[SampleQueryServiceTransport]] + _transport_registry["grpc"] = SampleQueryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SampleQueryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SampleQueryServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SampleQueryServiceTransport]: + """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 SampleQueryServiceClient(metaclass=SampleQueryServiceClientMeta): + """Service for managing + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SampleQueryServiceClient: 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: + SampleQueryServiceClient: 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) -> SampleQueryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQueryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def sample_query_path( + project: str, + location: str, + sample_query_set: str, + sample_query: str, + ) -> str: + """Returns a fully-qualified sample_query string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + + @staticmethod + def parse_sample_query_path(path: str) -> Dict[str, str]: + """Parses a sample_query path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)/sampleQueries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SampleQueryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or SampleQueryServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQueryServiceTransport, + Callable[..., SampleQueryServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQueryServiceTransport,Callable[..., SampleQueryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQueryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SampleQueryServiceClient._read_environment_variables() + self._client_cert_source = SampleQueryServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SampleQueryServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SampleQueryServiceTransport) + if transport_provided: + # transport is a SampleQueryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SampleQueryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SampleQueryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SampleQueryServiceTransport], + Callable[..., SampleQueryServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SampleQueryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_sample_query( + self, + request: Optional[ + Union[sample_query_service.GetSampleQueryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Gets a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery] + method. + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.GetSampleQueryRequest): + request = sample_query_service.GetSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sample_queries( + self, + request: Optional[ + Union[sample_query_service.ListSampleQueriesRequest, 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.ListSampleQueriesPager: + r"""Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesRequest, dict]): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + parent (str): + Required. The parent sample query set resource name, + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + under this sample query set, regardless of whether or + not this sample query set 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.sample_query_service.pagers.ListSampleQueriesPager: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.ListSampleQueriesRequest): + request = sample_query_service.ListSampleQueriesRequest(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_sample_queries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSampleQueriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sample_query( + self, + request: Optional[ + Union[sample_query_service.CreateSampleQueryRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query: Optional[gcd_sample_query.SampleQuery] = None, + sample_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Creates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = client.create_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query (google.cloud.discoveryengine_v1alpha.types.SampleQuery): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + to create. + + This corresponds to the ``sample_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_id (str): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1alpha.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQueryRequest.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 ``sample_query_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.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query, sample_query_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.CreateSampleQueryRequest): + request = sample_query_service.CreateSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query is not None: + request.sample_query = sample_query + if sample_query_id is not None: + request.sample_query_id = sample_query_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_sample_query( + self, + request: Optional[ + Union[sample_query_service.UpdateSampleQueryRequest, dict] + ] = None, + *, + sample_query: Optional[gcd_sample_query.SampleQuery] = 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_sample_query.SampleQuery: + r"""Updates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = client.update_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery] + method. + sample_query (google.cloud.discoveryengine_v1alpha.types.SampleQuery): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query`` 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 imported 'simple query' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.UpdateSampleQueryRequest): + request = sample_query_service.UpdateSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query is not None: + request.sample_query = sample_query + 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query.name", request.sample_query.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sample_query( + self, + request: Optional[ + Union[sample_query_service.DeleteSampleQueryRequest, dict] + ] = 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 + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery] + method. + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.DeleteSampleQueryRequest): + request = sample_query_service.DeleteSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_sample_queries( + self, + request: Optional[Union[import_config.ImportSampleQueriesRequest, 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 + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + to be successfully imported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ImportSampleQueriesRequest, dict]): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.ImportSampleQueriesResponse` Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportSampleQueriesRequest): + request = import_config.ImportSampleQueriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_sample_queries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportSampleQueriesResponse, + metadata_type=import_config.ImportSampleQueriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SampleQueryServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SampleQueryServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/pagers.py new file mode 100644 index 000000000000..dc6bcf742152 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query, + sample_query_service, +) + + +class ListSampleQueriesPager: + """A pager for iterating through ``list_sample_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sample_queries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSampleQueries`` requests and continue to iterate + through the ``sample_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse` + 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[..., sample_query_service.ListSampleQueriesResponse], + request: sample_query_service.ListSampleQueriesRequest, + response: sample_query_service.ListSampleQueriesResponse, + *, + 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.ListSampleQueriesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse): + 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 = sample_query_service.ListSampleQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[sample_query_service.ListSampleQueriesResponse]: + 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[sample_query.SampleQuery]: + for page in self.pages: + yield from page.sample_queries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSampleQueriesAsyncPager: + """A pager for iterating through ``list_sample_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sample_queries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSampleQueries`` requests and continue to iterate + through the ``sample_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse` + 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[sample_query_service.ListSampleQueriesResponse] + ], + request: sample_query_service.ListSampleQueriesRequest, + response: sample_query_service.ListSampleQueriesResponse, + *, + 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.ListSampleQueriesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesResponse): + 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 = sample_query_service.ListSampleQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[sample_query_service.ListSampleQueriesResponse]: + 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[sample_query.SampleQuery]: + async def async_generator(): + async for page in self.pages: + for response in page.sample_queries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/__init__.py new file mode 100644 index 000000000000..115e91897ac1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SampleQueryServiceTransport +from .grpc import SampleQueryServiceGrpcTransport +from .grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport +from .rest import SampleQueryServiceRestInterceptor, SampleQueryServiceRestTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SampleQueryServiceTransport]] +_transport_registry["grpc"] = SampleQueryServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SampleQueryServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SampleQueryServiceRestTransport + +__all__ = ( + "SampleQueryServiceTransport", + "SampleQueryServiceGrpcTransport", + "SampleQueryServiceGrpcAsyncIOTransport", + "SampleQueryServiceRestTransport", + "SampleQueryServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/base.py new file mode 100644 index 000000000000..a0f315c97e92 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/base.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SampleQueryServiceTransport(abc.ABC): + """Abstract transport class for SampleQueryService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_sample_query: gapic_v1.method.wrap_method( + self.get_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_queries: gapic_v1.method.wrap_method( + self.list_sample_queries, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query: gapic_v1.method.wrap_method( + self.create_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query: gapic_v1.method.wrap_method( + self.update_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query: gapic_v1.method.wrap_method( + self.delete_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.import_sample_queries: gapic_v1.method.wrap_method( + self.import_sample_queries, + 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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], + Union[sample_query.SampleQuery, Awaitable[sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + Union[ + sample_query_service.ListSampleQueriesResponse, + Awaitable[sample_query_service.ListSampleQueriesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], + Union[gcd_sample_query.SampleQuery, Awaitable[gcd_sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], + Union[gcd_sample_query.SampleQuery, Awaitable[gcd_sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def delete_sample_query( + self, + ) -> Callable[ + [sample_query_service.DeleteSampleQueryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def import_sample_queries( + self, + ) -> Callable[ + [import_config.ImportSampleQueriesRequest], + 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 cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SampleQueryServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc.py new file mode 100644 index 000000000000..89069c729d93 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc.py @@ -0,0 +1,496 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport + + +class SampleQueryServiceGrpcTransport(SampleQueryServiceTransport): + """gRPC backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], sample_query.SampleQuery + ]: + r"""Return a callable for the get sample query method over gRPC. + + Gets a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.GetSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query" not in self._stubs: + self._stubs["get_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/GetSampleQuery", + request_serializer=sample_query_service.GetSampleQueryRequest.serialize, + response_deserializer=sample_query.SampleQuery.deserialize, + ) + return self._stubs["get_sample_query"] + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + sample_query_service.ListSampleQueriesResponse, + ]: + r"""Return a callable for the list sample queries method over gRPC. + + Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + + Returns: + Callable[[~.ListSampleQueriesRequest], + ~.ListSampleQueriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["list_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/ListSampleQueries", + request_serializer=sample_query_service.ListSampleQueriesRequest.serialize, + response_deserializer=sample_query_service.ListSampleQueriesResponse.deserialize, + ) + return self._stubs["list_sample_queries"] + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + r"""Return a callable for the create sample query method over gRPC. + + Creates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + + Returns: + Callable[[~.CreateSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["create_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/CreateSampleQuery", + request_serializer=sample_query_service.CreateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["create_sample_query"] + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + r"""Return a callable for the update sample query method over gRPC. + + Updates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.UpdateSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["update_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/UpdateSampleQuery", + request_serializer=sample_query_service.UpdateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["update_sample_query"] + + @property + def delete_sample_query( + self, + ) -> Callable[[sample_query_service.DeleteSampleQueryRequest], empty_pb2.Empty]: + r"""Return a callable for the delete sample query method over gRPC. + + Deletes a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.DeleteSampleQueryRequest], + ~.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_sample_query" not in self._stubs: + self._stubs["delete_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/DeleteSampleQuery", + request_serializer=sample_query_service.DeleteSampleQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query"] + + @property + def import_sample_queries( + self, + ) -> Callable[[import_config.ImportSampleQueriesRequest], operations_pb2.Operation]: + r"""Return a callable for the import sample queries method over gRPC. + + Bulk import of multiple + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + to be successfully imported. + + Returns: + Callable[[~.ImportSampleQueriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["import_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/ImportSampleQueries", + request_serializer=import_config.ImportSampleQueriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_sample_queries"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SampleQueryServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..aa84e75f30e3 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/grpc_asyncio.py @@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .grpc import SampleQueryServiceGrpcTransport + + +class SampleQueryServiceGrpcAsyncIOTransport(SampleQueryServiceTransport): + """gRPC AsyncIO backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], + Awaitable[sample_query.SampleQuery], + ]: + r"""Return a callable for the get sample query method over gRPC. + + Gets a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.GetSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query" not in self._stubs: + self._stubs["get_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/GetSampleQuery", + request_serializer=sample_query_service.GetSampleQueryRequest.serialize, + response_deserializer=sample_query.SampleQuery.deserialize, + ) + return self._stubs["get_sample_query"] + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + Awaitable[sample_query_service.ListSampleQueriesResponse], + ]: + r"""Return a callable for the list sample queries method over gRPC. + + Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + + Returns: + Callable[[~.ListSampleQueriesRequest], + Awaitable[~.ListSampleQueriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["list_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/ListSampleQueries", + request_serializer=sample_query_service.ListSampleQueriesRequest.serialize, + response_deserializer=sample_query_service.ListSampleQueriesResponse.deserialize, + ) + return self._stubs["list_sample_queries"] + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], + Awaitable[gcd_sample_query.SampleQuery], + ]: + r"""Return a callable for the create sample query method over gRPC. + + Creates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + + Returns: + Callable[[~.CreateSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["create_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/CreateSampleQuery", + request_serializer=sample_query_service.CreateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["create_sample_query"] + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], + Awaitable[gcd_sample_query.SampleQuery], + ]: + r"""Return a callable for the update sample query method over gRPC. + + Updates a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.UpdateSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["update_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/UpdateSampleQuery", + request_serializer=sample_query_service.UpdateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["update_sample_query"] + + @property + def delete_sample_query( + self, + ) -> Callable[ + [sample_query_service.DeleteSampleQueryRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete sample query method over gRPC. + + Deletes a + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Returns: + Callable[[~.DeleteSampleQueryRequest], + 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_sample_query" not in self._stubs: + self._stubs["delete_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/DeleteSampleQuery", + request_serializer=sample_query_service.DeleteSampleQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query"] + + @property + def import_sample_queries( + self, + ) -> Callable[ + [import_config.ImportSampleQueriesRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the import sample queries method over gRPC. + + Bulk import of multiple + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + to be successfully imported. + + Returns: + Callable[[~.ImportSampleQueriesRequest], + 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_sample_queries" not in self._stubs: + self._stubs["import_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQueryService/ImportSampleQueries", + request_serializer=import_config.ImportSampleQueriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_sample_queries"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_sample_query: gapic_v1.method_async.wrap_method( + self.get_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_queries: gapic_v1.method_async.wrap_method( + self.list_sample_queries, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query: gapic_v1.method_async.wrap_method( + self.create_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query: gapic_v1.method_async.wrap_method( + self.update_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query: gapic_v1.method_async.wrap_method( + self.delete_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.import_sample_queries: gapic_v1.method_async.wrap_method( + self.import_sample_queries, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SampleQueryServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py new file mode 100644 index 000000000000..783cc3209c18 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py @@ -0,0 +1,1528 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import 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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SampleQueryServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SampleQueryServiceRestInterceptor: + """Interceptor for SampleQueryService. + + 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 SampleQueryServiceRestTransport. + + .. code-block:: python + class MyCustomSampleQueryServiceInterceptor(SampleQueryServiceRestInterceptor): + def pre_create_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_sample_queries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_sample_queries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sample_queries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sample_queries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SampleQueryServiceRestTransport(interceptor=MyCustomSampleQueryServiceInterceptor()) + client = SampleQueryServiceClient(transport=transport) + + + """ + + def pre_create_sample_query( + self, + request: sample_query_service.CreateSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.CreateSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_create_sample_query( + self, response: gcd_sample_query.SampleQuery + ) -> gcd_sample_query.SampleQuery: + """Post-rpc interceptor for create_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_delete_sample_query( + self, + request: sample_query_service.DeleteSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.DeleteSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def pre_get_sample_query( + self, + request: sample_query_service.GetSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[sample_query_service.GetSampleQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_get_sample_query( + self, response: sample_query.SampleQuery + ) -> sample_query.SampleQuery: + """Post-rpc interceptor for get_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_import_sample_queries( + self, + request: import_config.ImportSampleQueriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[import_config.ImportSampleQueriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_sample_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_import_sample_queries( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_sample_queries + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_list_sample_queries( + self, + request: sample_query_service.ListSampleQueriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.ListSampleQueriesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_sample_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_list_sample_queries( + self, response: sample_query_service.ListSampleQueriesResponse + ) -> sample_query_service.ListSampleQueriesResponse: + """Post-rpc interceptor for list_sample_queries + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_update_sample_query( + self, + request: sample_query_service.UpdateSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.UpdateSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_update_sample_query( + self, response: gcd_sample_query.SampleQuery + ) -> gcd_sample_query.SampleQuery: + """Post-rpc interceptor for update_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService 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 SampleQueryService 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 SampleQueryService 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 SampleQueryService 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 SampleQueryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SampleQueryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SampleQueryServiceRestInterceptor + + +class SampleQueryServiceRestTransport(SampleQueryServiceTransport): + """REST backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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[SampleQueryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 SampleQueryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataConnector/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/*/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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataConnector}/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/*/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 _CreateSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("CreateSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sampleQueryId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.CreateSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Call the create sample query method over HTTP. + + Args: + request (~.sample_query_service.CreateSampleQueryRequest): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/sampleQuerySets/*}/sampleQueries", + "body": "sample_query", + }, + ] + request, metadata = self._interceptor.pre_create_sample_query( + request, metadata + ) + pb_request = sample_query_service.CreateSampleQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query.SampleQuery() + pb_resp = gcd_sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sample_query(resp) + return resp + + class _DeleteSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("DeleteSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.DeleteSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete sample query method over HTTP. + + Args: + request (~.sample_query_service.DeleteSampleQueryRequest): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/sampleQuerySets/*/sampleQueries/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_sample_query( + request, metadata + ) + pb_request = sample_query_service.DeleteSampleQueryRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 _GetSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("GetSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.GetSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Call the get sample query method over HTTP. + + Args: + request (~.sample_query_service.GetSampleQueryRequest): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}", + }, + ] + request, metadata = self._interceptor.pre_get_sample_query( + request, metadata + ) + pb_request = sample_query_service.GetSampleQueryRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query.SampleQuery() + pb_resp = sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_sample_query(resp) + return resp + + class _ImportSampleQueries(SampleQueryServiceRestStub): + def __hash__(self): + return hash("ImportSampleQueries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_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.ImportSampleQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the import sample queries method over HTTP. + + Args: + request (~.import_config.ImportSampleQueriesRequest): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The 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/*/sampleQuerySets/*}/sampleQueries:import", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_import_sample_queries( + request, metadata + ) + pb_request = import_config.ImportSampleQueriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_queries(resp) + return resp + + class _ListSampleQueries(SampleQueryServiceRestStub): + def __hash__(self): + return hash("ListSampleQueries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.ListSampleQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_service.ListSampleQueriesResponse: + r"""Call the list sample queries method over HTTP. + + Args: + request (~.sample_query_service.ListSampleQueriesRequest): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_service.ListSampleQueriesResponse: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*/sampleQuerySets/*}/sampleQueries", + }, + ] + request, metadata = self._interceptor.pre_list_sample_queries( + request, metadata + ) + pb_request = sample_query_service.ListSampleQueriesRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_service.ListSampleQueriesResponse() + pb_resp = sample_query_service.ListSampleQueriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sample_queries(resp) + return resp + + class _UpdateSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("UpdateSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.UpdateSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Call the update sample query method over HTTP. + + Args: + request (~.sample_query_service.UpdateSampleQueryRequest): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{sample_query.name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}", + "body": "sample_query", + }, + ] + request, metadata = self._interceptor.pre_update_sample_query( + request, metadata + ) + pb_request = sample_query_service.UpdateSampleQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query.SampleQuery() + pb_resp = gcd_sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_sample_query(resp) + return resp + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sample_query( + self, + ) -> Callable[[sample_query_service.DeleteSampleQueryRequest], 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._DeleteSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_sample_queries( + self, + ) -> Callable[[import_config.ImportSampleQueriesRequest], 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._ImportSampleQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + sample_query_service.ListSampleQueriesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSampleQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SampleQueryServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SampleQueryServiceRestStub): + 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/*/dataConnector/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/*/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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/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(SampleQueryServiceRestStub): + 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/*/dataConnector}/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/*/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__ = ("SampleQueryServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/__init__.py new file mode 100644 index 000000000000..59b993474e98 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SampleQuerySetServiceAsyncClient +from .client import SampleQuerySetServiceClient + +__all__ = ( + "SampleQuerySetServiceClient", + "SampleQuerySetServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/async_client.py new file mode 100644 index 000000000000..4b9b515aed07 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/async_client.py @@ -0,0 +1,1132 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.sample_query_set_service import ( + pagers, +) +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +from .client import SampleQuerySetServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .transports.grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport + + +class SampleQuerySetServiceAsyncClient: + """Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s, + """ + + _client: SampleQuerySetServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SampleQuerySetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + + location_path = staticmethod(SampleQuerySetServiceClient.location_path) + parse_location_path = staticmethod(SampleQuerySetServiceClient.parse_location_path) + sample_query_set_path = staticmethod( + SampleQuerySetServiceClient.sample_query_set_path + ) + parse_sample_query_set_path = staticmethod( + SampleQuerySetServiceClient.parse_sample_query_set_path + ) + common_billing_account_path = staticmethod( + SampleQuerySetServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SampleQuerySetServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SampleQuerySetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SampleQuerySetServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SampleQuerySetServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SampleQuerySetServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SampleQuerySetServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SampleQuerySetServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SampleQuerySetServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SampleQuerySetServiceClient.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: + SampleQuerySetServiceAsyncClient: The constructed client. + """ + return SampleQuerySetServiceClient.from_service_account_info.__func__(SampleQuerySetServiceAsyncClient, 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: + SampleQuerySetServiceAsyncClient: The constructed client. + """ + return SampleQuerySetServiceClient.from_service_account_file.__func__(SampleQuerySetServiceAsyncClient, 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 SampleQuerySetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SampleQuerySetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQuerySetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(SampleQuerySetServiceClient).get_transport_class, + type(SampleQuerySetServiceClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQuerySetServiceTransport, + Callable[..., SampleQuerySetServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query set service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQuerySetServiceTransport,Callable[..., SampleQuerySetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQuerySetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SampleQuerySetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.GetSampleQuerySetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.GetSampleQuerySetRequest): + request = sample_query_set_service.GetSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sample_query_sets( + self, + request: Optional[ + Union[sample_query_set_service.ListSampleQuerySetsRequest, 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.ListSampleQuerySetsAsyncPager: + r"""Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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_sample_query_sets(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + parent (:class:`str`): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + under this location, regardless of whether or not this + location 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.ListSampleQuerySetsRequest): + request = sample_query_set_service.ListSampleQuerySetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sample_query_sets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSampleQuerySetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.CreateSampleQuerySetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = None, + sample_query_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = await client.create_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set (:class:`google.cloud.discoveryengine_v1alpha.types.SampleQuerySet`): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + to create. + + This corresponds to the ``sample_query_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set_id (:class:`str`): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1alpha.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQuerySetRequest.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 ``sample_query_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query_set, sample_query_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.CreateSampleQuerySetRequest + ): + request = sample_query_set_service.CreateSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if sample_query_set_id is not None: + request.sample_query_set_id = sample_query_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.UpdateSampleQuerySetRequest, dict] + ] = None, + *, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = 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_sample_query_set.SampleQuerySet: + r"""Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = await client.update_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet] + method. + sample_query_set (:class:`google.cloud.discoveryengine_v1alpha.types.SampleQuerySet`): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query_set`` 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 imported 'sample query set' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.UpdateSampleQuerySetRequest + ): + request = sample_query_set_service.UpdateSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query_set.name", request.sample_query_set.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.DeleteSampleQuerySetRequest, dict] + ] = 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 + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query_set(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.DeleteSampleQuerySetRequest + ): + request = sample_query_set_service.DeleteSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SampleQuerySetServiceAsyncClient": + 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__ = ("SampleQuerySetServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/client.py new file mode 100644 index 000000000000..8f1abe999da9 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/client.py @@ -0,0 +1,1555 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.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 google.cloud.discoveryengine_v1alpha.services.sample_query_set_service import ( + pagers, +) +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +from .transports.base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .transports.grpc import SampleQuerySetServiceGrpcTransport +from .transports.grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport +from .transports.rest import SampleQuerySetServiceRestTransport + + +class SampleQuerySetServiceClientMeta(type): + """Metaclass for the SampleQuerySetService 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[SampleQuerySetServiceTransport]] + _transport_registry["grpc"] = SampleQuerySetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SampleQuerySetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SampleQuerySetServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SampleQuerySetServiceTransport]: + """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 SampleQuerySetServiceClient(metaclass=SampleQuerySetServiceClientMeta): + """Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SampleQuerySetServiceClient: 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: + SampleQuerySetServiceClient: 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) -> SampleQuerySetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQuerySetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def 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_location_path(path: str) -> Dict[str, str]: + """Parses a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or SampleQuerySetServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQuerySetServiceTransport, + Callable[..., SampleQuerySetServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query set service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQuerySetServiceTransport,Callable[..., SampleQuerySetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQuerySetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SampleQuerySetServiceClient._read_environment_variables() + self._client_cert_source = SampleQuerySetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SampleQuerySetServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SampleQuerySetServiceTransport) + if transport_provided: + # transport is a SampleQuerySetServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SampleQuerySetServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SampleQuerySetServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SampleQuerySetServiceTransport], + Callable[..., SampleQuerySetServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SampleQuerySetServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.GetSampleQuerySetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet] + method. + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.GetSampleQuerySetRequest): + request = sample_query_set_service.GetSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sample_query_sets( + self, + request: Optional[ + Union[sample_query_set_service.ListSampleQuerySetsRequest, 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.ListSampleQuerySetsPager: + r"""Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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_sample_query_sets(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsRequest, dict]): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + under this location, regardless of whether or not this + location 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.sample_query_set_service.pagers.ListSampleQuerySetsPager: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.ListSampleQuerySetsRequest): + request = sample_query_set_service.ListSampleQuerySetsRequest(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_sample_query_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSampleQuerySetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.CreateSampleQuerySetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = None, + sample_query_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = client.create_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set (google.cloud.discoveryengine_v1alpha.types.SampleQuerySet): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + to create. + + This corresponds to the ``sample_query_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set_id (str): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1alpha.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQuerySetRequest.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 ``sample_query_set_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.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query_set, sample_query_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.CreateSampleQuerySetRequest + ): + request = sample_query_set_service.CreateSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if sample_query_set_id is not None: + request.sample_query_set_id = sample_query_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.UpdateSampleQuerySetRequest, dict] + ] = None, + *, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = 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_sample_query_set.SampleQuerySet: + r"""Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = client.update_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet] + method. + sample_query_set (google.cloud.discoveryengine_v1alpha.types.SampleQuerySet): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query_set`` 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 imported 'sample query set' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.UpdateSampleQuerySetRequest + ): + request = sample_query_set_service.UpdateSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query_set is not None: + request.sample_query_set = sample_query_set + 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query_set.name", request.sample_query_set.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.DeleteSampleQuerySetRequest, dict] + ] = 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 + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query_set(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet] + method. + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.DeleteSampleQuerySetRequest + ): + request = sample_query_set_service.DeleteSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "SampleQuerySetServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SampleQuerySetServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/pagers.py new file mode 100644 index 000000000000..d5d971267763 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set, + sample_query_set_service, +) + + +class ListSampleQuerySetsPager: + """A pager for iterating through ``list_sample_query_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sample_query_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSampleQuerySets`` requests and continue to iterate + through the ``sample_query_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse` + 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[..., sample_query_set_service.ListSampleQuerySetsResponse], + request: sample_query_set_service.ListSampleQuerySetsRequest, + response: sample_query_set_service.ListSampleQuerySetsResponse, + *, + 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.ListSampleQuerySetsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse): + 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 = sample_query_set_service.ListSampleQuerySetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[sample_query_set_service.ListSampleQuerySetsResponse]: + 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[sample_query_set.SampleQuerySet]: + for page in self.pages: + yield from page.sample_query_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSampleQuerySetsAsyncPager: + """A pager for iterating through ``list_sample_query_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sample_query_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSampleQuerySets`` requests and continue to iterate + through the ``sample_query_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse` + 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[sample_query_set_service.ListSampleQuerySetsResponse] + ], + request: sample_query_set_service.ListSampleQuerySetsRequest, + response: sample_query_set_service.ListSampleQuerySetsResponse, + *, + 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.ListSampleQuerySetsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsResponse): + 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 = sample_query_set_service.ListSampleQuerySetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[sample_query_set_service.ListSampleQuerySetsResponse]: + 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[sample_query_set.SampleQuerySet]: + async def async_generator(): + async for page in self.pages: + for response in page.sample_query_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/__init__.py new file mode 100644 index 000000000000..63205c014885 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 SampleQuerySetServiceTransport +from .grpc import SampleQuerySetServiceGrpcTransport +from .grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport +from .rest import ( + SampleQuerySetServiceRestInterceptor, + SampleQuerySetServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SampleQuerySetServiceTransport]] +_transport_registry["grpc"] = SampleQuerySetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SampleQuerySetServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SampleQuerySetServiceRestTransport + +__all__ = ( + "SampleQuerySetServiceTransport", + "SampleQuerySetServiceGrpcTransport", + "SampleQuerySetServiceGrpcAsyncIOTransport", + "SampleQuerySetServiceRestTransport", + "SampleQuerySetServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/base.py new file mode 100644 index 000000000000..c224bf9eecc9 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/base.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SampleQuerySetServiceTransport(abc.ABC): + """Abstract transport class for SampleQuerySetService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_sample_query_set: gapic_v1.method.wrap_method( + self.get_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_query_sets: gapic_v1.method.wrap_method( + self.list_sample_query_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query_set: gapic_v1.method.wrap_method( + self.create_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query_set: gapic_v1.method.wrap_method( + self.update_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query_set: gapic_v1.method.wrap_method( + self.delete_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + Union[ + sample_query_set.SampleQuerySet, Awaitable[sample_query_set.SampleQuerySet] + ], + ]: + raise NotImplementedError() + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + Union[ + sample_query_set_service.ListSampleQuerySetsResponse, + Awaitable[sample_query_set_service.ListSampleQuerySetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + Union[ + gcd_sample_query_set.SampleQuerySet, + Awaitable[gcd_sample_query_set.SampleQuerySet], + ], + ]: + raise NotImplementedError() + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + Union[ + gcd_sample_query_set.SampleQuerySet, + Awaitable[gcd_sample_query_set.SampleQuerySet], + ], + ]: + raise NotImplementedError() + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SampleQuerySetServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc.py new file mode 100644 index 000000000000..ac40de722a5e --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +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 +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport + + +class SampleQuerySetServiceGrpcTransport(SampleQuerySetServiceTransport): + """gRPC backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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 get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the get sample query set method over gRPC. + + Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.GetSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query_set" not in self._stubs: + self._stubs["get_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/GetSampleQuerySet", + request_serializer=sample_query_set_service.GetSampleQuerySetRequest.serialize, + response_deserializer=sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["get_sample_query_set"] + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + sample_query_set_service.ListSampleQuerySetsResponse, + ]: + r"""Return a callable for the list sample query sets method over gRPC. + + Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s. + + Returns: + Callable[[~.ListSampleQuerySetsRequest], + ~.ListSampleQuerySetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_sets" not in self._stubs: + self._stubs["list_sample_query_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/ListSampleQuerySets", + request_serializer=sample_query_set_service.ListSampleQuerySetsRequest.serialize, + response_deserializer=sample_query_set_service.ListSampleQuerySetsResponse.deserialize, + ) + return self._stubs["list_sample_query_sets"] + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the create sample query set method over gRPC. + + Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + + Returns: + Callable[[~.CreateSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["create_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/CreateSampleQuerySet", + request_serializer=sample_query_set_service.CreateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["create_sample_query_set"] + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the update sample query set method over gRPC. + + Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.UpdateSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["update_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/UpdateSampleQuerySet", + request_serializer=sample_query_set_service.UpdateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["update_sample_query_set"] + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete sample query set method over gRPC. + + Deletes a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.DeleteSampleQuerySetRequest], + ~.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_sample_query_set" not in self._stubs: + self._stubs["delete_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/DeleteSampleQuerySet", + request_serializer=sample_query_set_service.DeleteSampleQuerySetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query_set"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SampleQuerySetServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3c33b2f1fe00 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/grpc_asyncio.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .grpc import SampleQuerySetServiceGrpcTransport + + +class SampleQuerySetServiceGrpcAsyncIOTransport(SampleQuerySetServiceTransport): + """gRPC AsyncIO backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + Awaitable[sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the get sample query set method over gRPC. + + Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.GetSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query_set" not in self._stubs: + self._stubs["get_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/GetSampleQuerySet", + request_serializer=sample_query_set_service.GetSampleQuerySetRequest.serialize, + response_deserializer=sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["get_sample_query_set"] + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + Awaitable[sample_query_set_service.ListSampleQuerySetsResponse], + ]: + r"""Return a callable for the list sample query sets method over gRPC. + + Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s. + + Returns: + Callable[[~.ListSampleQuerySetsRequest], + Awaitable[~.ListSampleQuerySetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_sets" not in self._stubs: + self._stubs["list_sample_query_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/ListSampleQuerySets", + request_serializer=sample_query_set_service.ListSampleQuerySetsRequest.serialize, + response_deserializer=sample_query_set_service.ListSampleQuerySetsResponse.deserialize, + ) + return self._stubs["list_sample_query_sets"] + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + Awaitable[gcd_sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the create sample query set method over gRPC. + + Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + + Returns: + Callable[[~.CreateSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["create_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/CreateSampleQuerySet", + request_serializer=sample_query_set_service.CreateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["create_sample_query_set"] + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + Awaitable[gcd_sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the update sample query set method over gRPC. + + Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.UpdateSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["update_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/UpdateSampleQuerySet", + request_serializer=sample_query_set_service.UpdateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["update_sample_query_set"] + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete sample query set method over gRPC. + + Deletes a + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Returns: + Callable[[~.DeleteSampleQuerySetRequest], + 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_sample_query_set" not in self._stubs: + self._stubs["delete_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SampleQuerySetService/DeleteSampleQuerySet", + request_serializer=sample_query_set_service.DeleteSampleQuerySetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query_set"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_sample_query_set: gapic_v1.method_async.wrap_method( + self.get_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_query_sets: gapic_v1.method_async.wrap_method( + self.list_sample_query_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query_set: gapic_v1.method_async.wrap_method( + self.create_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query_set: gapic_v1.method_async.wrap_method( + self.update_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query_set: gapic_v1.method_async.wrap_method( + self.delete_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SampleQuerySetServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py new file mode 100644 index 000000000000..a8e81cc246bf --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py @@ -0,0 +1,1241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SampleQuerySetServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SampleQuerySetServiceRestInterceptor: + """Interceptor for SampleQuerySetService. + + 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 SampleQuerySetServiceRestTransport. + + .. code-block:: python + class MyCustomSampleQuerySetServiceInterceptor(SampleQuerySetServiceRestInterceptor): + def pre_create_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sample_query_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sample_query_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SampleQuerySetServiceRestTransport(interceptor=MyCustomSampleQuerySetServiceInterceptor()) + client = SampleQuerySetServiceClient(transport=transport) + + + """ + + def pre_create_sample_query_set( + self, + request: sample_query_set_service.CreateSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.CreateSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_create_sample_query_set( + self, response: gcd_sample_query_set.SampleQuerySet + ) -> gcd_sample_query_set.SampleQuerySet: + """Post-rpc interceptor for create_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_delete_sample_query_set( + self, + request: sample_query_set_service.DeleteSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.DeleteSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def pre_get_sample_query_set( + self, + request: sample_query_set_service.GetSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.GetSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_get_sample_query_set( + self, response: sample_query_set.SampleQuerySet + ) -> sample_query_set.SampleQuerySet: + """Post-rpc interceptor for get_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_list_sample_query_sets( + self, + request: sample_query_set_service.ListSampleQuerySetsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.ListSampleQuerySetsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_sample_query_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_list_sample_query_sets( + self, response: sample_query_set_service.ListSampleQuerySetsResponse + ) -> sample_query_set_service.ListSampleQuerySetsResponse: + """Post-rpc interceptor for list_sample_query_sets + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_update_sample_query_set( + self, + request: sample_query_set_service.UpdateSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.UpdateSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_update_sample_query_set( + self, response: gcd_sample_query_set.SampleQuerySet + ) -> gcd_sample_query_set.SampleQuerySet: + """Post-rpc interceptor for update_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SampleQuerySetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SampleQuerySetServiceRestInterceptor + + +class SampleQuerySetServiceRestTransport(SampleQuerySetServiceTransport): + """REST backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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[SampleQuerySetServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 SampleQuerySetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("CreateSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sampleQuerySetId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.CreateSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Call the create sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.CreateSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}/sampleQuerySets", + "body": "sample_query_set", + }, + ] + request, metadata = self._interceptor.pre_create_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.CreateSampleQuerySetRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query_set.SampleQuerySet() + pb_resp = gcd_sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sample_query_set(resp) + return resp + + class _DeleteSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("DeleteSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.DeleteSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.DeleteSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/sampleQuerySets/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.DeleteSampleQuerySetRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 _GetSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("GetSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.GetSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Call the get sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.GetSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.GetSampleQuerySetRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_set.SampleQuerySet() + pb_resp = sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_sample_query_set(resp) + return resp + + class _ListSampleQuerySets(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("ListSampleQuerySets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.ListSampleQuerySetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set_service.ListSampleQuerySetsResponse: + r"""Call the list sample query sets method over HTTP. + + Args: + request (~.sample_query_set_service.ListSampleQuerySetsRequest): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_set_service.ListSampleQuerySetsResponse: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}/sampleQuerySets", + }, + ] + request, metadata = self._interceptor.pre_list_sample_query_sets( + request, metadata + ) + pb_request = sample_query_set_service.ListSampleQuerySetsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_set_service.ListSampleQuerySetsResponse() + pb_resp = sample_query_set_service.ListSampleQuerySetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sample_query_sets(resp) + return resp + + class _UpdateSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("UpdateSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.UpdateSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Call the update sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.UpdateSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{sample_query_set.name=projects/*/locations/*/sampleQuerySets/*}", + "body": "sample_query_set", + }, + ] + request, metadata = self._interceptor.pre_update_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.UpdateSampleQuerySetRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query_set.SampleQuerySet() + pb_resp = gcd_sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_sample_query_set(resp) + return resp + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], 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._DeleteSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + sample_query_set_service.ListSampleQuerySetsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSampleQuerySets(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SampleQuerySetServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SampleQuerySetServiceRestStub): + 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/*/dataConnector/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/*/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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/sampleQuerySets/*/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(SampleQuerySetServiceRestStub): + 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/*/dataConnector}/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/*/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__ = ("SampleQuerySetServiceRestTransport",) 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 97c2518c9a70..733193e2dee8 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 @@ -117,6 +117,16 @@ EstimateDataSizeRequest, EstimateDataSizeResponse, ) +from .evaluation import Evaluation, QualityMetrics +from .evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) from .grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, @@ -135,6 +145,9 @@ ImportDocumentsRequest, ImportDocumentsResponse, ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, ImportSuggestionDenyListEntriesMetadata, ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, @@ -164,6 +177,24 @@ ) from .rank_service import RankingRecord, RankRequest, RankResponse from .recommendation_service import RecommendRequest, RecommendResponse +from .sample_query import SampleQuery +from .sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from .sample_query_set import SampleQuerySet +from .sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) from .schema import FieldConfig, Schema from .schema_service import ( CreateSchemaMetadata, @@ -329,6 +360,15 @@ "EstimateDataSizeMetadata", "EstimateDataSizeRequest", "EstimateDataSizeResponse", + "Evaluation", + "QualityMetrics", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "GetEvaluationRequest", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", @@ -345,6 +385,9 @@ "ImportDocumentsRequest", "ImportDocumentsResponse", "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", "ImportSuggestionDenyListEntriesMetadata", "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", @@ -372,6 +415,20 @@ "RankResponse", "RecommendRequest", "RecommendResponse", + "SampleQuery", + "CreateSampleQueryRequest", + "DeleteSampleQueryRequest", + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "UpdateSampleQueryRequest", + "SampleQuerySet", + "CreateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "UpdateSampleQuerySetRequest", "FieldConfig", "Schema", "CreateSchemaMetadata", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation.py new file mode 100644 index 000000000000..dbd9f7f5508f --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import search_service + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "Evaluation", + "QualityMetrics", + }, +) + + +class Evaluation(proto.Message): + r"""An evaluation is a single execution (or run) of an evaluation + process. It encapsulates the state of the evaluation and the + resulting data. + + Attributes: + name (str): + Identifier. The full resource name of the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + in the format of + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + evaluation_spec (google.cloud.discoveryengine_v1alpha.types.Evaluation.EvaluationSpec): + Required. The specification of the + evaluation. + quality_metrics (google.cloud.discoveryengine_v1alpha.types.QualityMetrics): + Output only. The metrics produced by the evaluation, + averaged across all + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + in the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + + Only populated when the evaluation's state is SUCCEEDED. + state (google.cloud.discoveryengine_v1alpha.types.Evaluation.State): + Output only. The state of the evaluation. + error (google.rpc.status_pb2.Status): + Output only. The error that occurred during + evaluation. Only populated when the evaluation's + state is FAILED. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + was created at. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + was completed at. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + Output only. A sample of errors encountered + while processing the request. + """ + + class State(proto.Enum): + r"""Describes the state of an evaluation. + + Values: + STATE_UNSPECIFIED (0): + The evaluation is unspecified. + PENDING (1): + The service is preparing to run the + evaluation. + RUNNING (2): + The evaluation is in progress. + SUCCEEDED (3): + The evaluation completed successfully. + FAILED (4): + The evaluation failed. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + FAILED = 4 + + class EvaluationSpec(proto.Message): + r"""Describes the specification of the evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_request (google.cloud.discoveryengine_v1alpha.types.SearchRequest): + Required. The search request that is used to perform the + evaluation. + + Only the following fields within SearchRequest are + supported; if any other fields are provided, an UNSUPPORTED + error will be returned: + + - [SearchRequest.serving_config][google.cloud.discoveryengine.v1alpha.SearchRequest.serving_config] + - [SearchRequest.branch][google.cloud.discoveryengine.v1alpha.SearchRequest.branch] + - [SearchRequest.canonical_filter][google.cloud.discoveryengine.v1alpha.SearchRequest.canonical_filter] + - [SearchRequest.query_expansion_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.query_expansion_spec] + - [SearchRequest.spell_correction_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.spell_correction_spec] + - [SearchRequest.content_search_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.content_search_spec] + - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1alpha.SearchRequest.user_pseudo_id] + + This field is a member of `oneof`_ ``search_spec``. + query_set_spec (google.cloud.discoveryengine_v1alpha.types.Evaluation.EvaluationSpec.QuerySetSpec): + Required. The specification of the query set. + """ + + class QuerySetSpec(proto.Message): + r"""Describes the specification of the query set. + + Attributes: + sample_query_set (str): + Required. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + used for the evaluation, in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + """ + + sample_query_set: str = proto.Field( + proto.STRING, + number=1, + ) + + search_request: search_service.SearchRequest = proto.Field( + proto.MESSAGE, + number=2, + oneof="search_spec", + message=search_service.SearchRequest, + ) + query_set_spec: "Evaluation.EvaluationSpec.QuerySetSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="Evaluation.EvaluationSpec.QuerySetSpec", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_spec: EvaluationSpec = proto.Field( + proto.MESSAGE, + number=2, + message=EvaluationSpec, + ) + quality_metrics: "QualityMetrics" = proto.Field( + proto.MESSAGE, + number=3, + message="QualityMetrics", + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + message=status_pb2.Status, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=status_pb2.Status, + ) + + +class QualityMetrics(proto.Message): + r"""Describes the metrics produced by the evaluation. + + Attributes: + doc_recall (google.cloud.discoveryengine_v1alpha.types.QualityMetrics.TopkMetrics): + Recall per document, at various top-k cutoff levels. + + Recall is the fraction of relevant documents retrieved out + of all relevant documents. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + If 3 out of 5 relevant documents are retrieved in the + top-5, recall@5 = 3/5 = 0.6 + doc_precision (google.cloud.discoveryengine_v1alpha.types.QualityMetrics.TopkMetrics): + Precision per document, at various top-k cutoff levels. + + Precision is the fraction of retrieved documents that are + relevant. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + If 4 out of 5 retrieved documents in the top-5 are + relevant, precision@5 = 4/5 = 0.8 + doc_ndcg (google.cloud.discoveryengine_v1alpha.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per document, + at various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + with three retrieved documents (D1, D2, D3) and binary + relevance judgements (1 for relevant, 0 for not relevant): + + Retrieved: [D3 (0), D1 (1), D2 (1)] Ideal: [D1 (1), D2 (1), + D3 (0)] + + Calculate NDCG@3 for each + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + page_recall (google.cloud.discoveryengine_v1alpha.types.QualityMetrics.TopkMetrics): + Recall per page, at various top-k cutoff levels. + + Recall is the fraction of relevant pages retrieved out of + all relevant pages. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + if 3 out of 5 relevant pages are retrieved in the top-5, + recall@5 = 3/5 = 0.6 + page_ndcg (google.cloud.discoveryengine_v1alpha.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per page, at + various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + with three retrieved pages (P1, P2, P3) and binary relevance + judgements (1 for relevant, 0 for not relevant): + + Retrieved: [P3 (0), P1 (1), P2 (1)] Ideal: [P1 (1), P2 (1), + P3 (0)] + + Calculate NDCG@3 for + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + """ + + class TopkMetrics(proto.Message): + r"""Stores the metric values at specific top-k levels. + + Attributes: + top_1 (float): + The top-1 value. + top_3 (float): + The top-3 value. + top_5 (float): + The top-5 value. + top_10 (float): + The top-10 value. + """ + + top_1: float = proto.Field( + proto.DOUBLE, + number=1, + ) + top_3: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_5: float = proto.Field( + proto.DOUBLE, + number=3, + ) + top_10: float = proto.Field( + proto.DOUBLE, + number=4, + ) + + doc_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=1, + message=TopkMetrics, + ) + doc_precision: TopkMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=TopkMetrics, + ) + doc_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=3, + message=TopkMetrics, + ) + page_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=4, + message=TopkMetrics, + ) + page_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=5, + message=TopkMetrics, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation_service.py new file mode 100644 index 000000000000..af5590db1c53 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/evaluation_service.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "GetEvaluationRequest", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "CreateEvaluationRequest", + "CreateEvaluationMetadata", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + }, +) + + +class GetEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation] + method. + + Attributes: + name (str): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]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 + [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + 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 ListEvaluationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations] + method. + + Attributes: + evaluations (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Evaluation]): + The + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationsRequest.page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_evaluation.Evaluation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + evaluation (google.cloud.discoveryengine_v1alpha.types.Evaluation): + Required. The + [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation] + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation: gcd_evaluation.Evaluation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.Evaluation, + ) + + +class CreateEvaluationMetadata(proto.Message): + r"""Metadata for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation] + method. + + """ + + +class ListEvaluationResultsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation (str): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless of + whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of [EvaluationResult][] 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 + [ListEvaluationResultsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationResultsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + evaluation: 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 ListEvaluationResultsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation_results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsResponse.EvaluationResult]): + The + [EvaluationResult][google.cloud.discoveryengine.v1alpha.ListEvaluationResultsResponse.EvaluationResult]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationResultsRequest.page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationResultsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + class EvaluationResult(proto.Message): + r"""Represents the results of an evaluation for a single + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + + Attributes: + sample_query (google.cloud.discoveryengine_v1alpha.types.SampleQuery): + Output only. The + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + that was evaluated. + quality_metrics (google.cloud.discoveryengine_v1alpha.types.QualityMetrics): + Output only. The metrics produced by the evaluation, for a + given + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + quality_metrics: gcd_evaluation.QualityMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.QualityMetrics, + ) + + @property + def raw_page(self): + return self + + evaluation_results: MutableSequence[EvaluationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=EvaluationResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py index 68961fb998de..8926d209b780 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py @@ -23,7 +23,12 @@ from google.type import date_pb2 # type: ignore import proto # type: ignore -from google.cloud.discoveryengine_v1alpha.types import completion, document, user_event +from google.cloud.discoveryengine_v1alpha.types import ( + completion, + document, + sample_query, + user_event, +) __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1alpha", @@ -46,6 +51,9 @@ "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", "ImportSuggestionDenyListEntriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", + "ImportSampleQueriesMetadata", }, ) @@ -1213,4 +1221,167 @@ class ImportSuggestionDenyListEntriesMetadata(proto.Message): ) +class ImportSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. + + 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.ImportSampleQueriesRequest.InlineSource): + The Inline source for sample query entries. + + 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 sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + class InlineSource(proto.Message): + r"""The inline source for + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SampleQuery]): + Required. A list of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + to import. Max of 1000 items. + """ + + sample_queries: MutableSequence[sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=sample_query.SampleQuery, + ) + + 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 ImportSampleQueriesResponse(proto.Message): + r"""Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this message is + returned by the google.longrunning.Operations.response field if the + operation is 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): + The desired location of errors incurred + during the Import. + """ + + 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", + ) + + +class ImportSampleQueriesMetadata(proto.Message): + r"""Metadata related to the progress of the ImportSampleQueries + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation last update + time. If the operation is done, this is also the + finish time. + success_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + successfully imported. + failure_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + that failed to be imported. + total_count (int): + Total count of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + that were processed. + """ + + 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, + ) + total_count: int = proto.Field( + proto.INT64, + number=5, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query.py new file mode 100644 index 000000000000..cc7d98db385a --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "SampleQuery", + }, +) + + +class SampleQuery(proto.Message): + r"""Sample Query captures metadata to be used for evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_entry (google.cloud.discoveryengine_v1alpha.types.SampleQuery.QueryEntry): + The query entry. + + This field is a member of `oneof`_ ``content``. + name (str): + Identifier. The full resource name of the sample query, in + the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + was created at. + """ + + class QueryEntry(proto.Message): + r"""Query Entry captures metadata to be used for search + evaluation. + + Attributes: + query (str): + Required. The query. + targets (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SampleQuery.QueryEntry.Target]): + List of targets for the query. + """ + + class Target(proto.Message): + r"""Defines the parameters of the query's expected outcome. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Expected uri of the target. + + This field must be a UTF-8 encoded string with a length + limit of 2048 characters. + + Example of valid uris: ``https://example.com/abc``, + ``gcs://example/example.pdf``. + page_numbers (MutableSequence[int]): + Expected page numbers of the target. + + Each page number must be non negative. + score (float): + Relevance score of the target. + + This field is a member of `oneof`_ ``_score``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + page_numbers: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + score: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + query: str = proto.Field( + proto.STRING, + number=1, + ) + targets: MutableSequence["SampleQuery.QueryEntry.Target"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SampleQuery.QueryEntry.Target", + ) + + query_entry: QueryEntry = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message=QueryEntry, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_service.py new file mode 100644 index 000000000000..c9fa1c9169bb --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_service.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "CreateSampleQueryRequest", + "UpdateSampleQueryRequest", + "DeleteSampleQueryRequest", + }, +) + + +class GetSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + + Attributes: + parent (str): + Required. The parent sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + page_size (int): + Maximum number of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]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 + [ListSampleQueriesResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListSampleQueriesResponse.next_page_token], + received from a previous + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + 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 ListSampleQueriesResponse(proto.Message): + r"""Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries] + method. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SampleQuery]): + The + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s. + next_page_token (str): + A token that can be sent as + [ListSampleQueriesRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSampleQueriesRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_queries: MutableSequence[gcd_sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + sample_query (google.cloud.discoveryengine_v1alpha.types.SampleQuery): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + to create. + sample_query_id (str): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1alpha.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQueryRequest.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, + ) + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query.SampleQuery, + ) + sample_query_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery] + method. + + Attributes: + sample_query (google.cloud.discoveryengine_v1alpha.types.SampleQuery): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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 + imported 'simple query' to update. If not set, + will by default update all fields. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1alpha.SampleQuery] + 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/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set.py new file mode 100644 index 000000000000..9a1200929e3f --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "SampleQuerySet", + }, +) + + +class SampleQuerySet(proto.Message): + r"""A SampleQuerySet is the parent resource of SampleQuery, and + contains the configurations shared by all SampleQuery under it. + + Attributes: + name (str): + Identifier. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + display_name (str): + Required. The sample query set display name. + + This field must be a UTF-8 encoded string with a + length limit of 128 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + was created at. + description (str): + The description of the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]. + """ + + 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, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set_service.py new file mode 100644 index 000000000000..500c2c3a71e7 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/sample_query_set_service.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1alpha", + manifest={ + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "CreateSampleQuerySetRequest", + "UpdateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + }, +) + + +class GetSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQuerySetsRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]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 + [ListSampleQuerySetsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListSampleQuerySetsResponse.next_page_token], + received from a previous + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + 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 ListSampleQuerySetsResponse(proto.Message): + r"""Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + sample_query_sets (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SampleQuerySet]): + The + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s. + next_page_token (str): + A token that can be sent as + [ListSampleQuerySetsRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSampleQuerySetsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_query_sets: MutableSequence[ + gcd_sample_query_set.SampleQuerySet + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + sample_query_set (google.cloud.discoveryengine_v1alpha.types.SampleQuerySet): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + to create. + sample_query_set_id (str): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1alpha.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateSampleQuerySetRequest.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, + ) + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query_set.SampleQuerySet, + ) + sample_query_set_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet] + method. + + Attributes: + sample_query_set (google.cloud.discoveryengine_v1alpha.types.SampleQuerySet): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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 + imported 'sample query set' to update. If not + set, will by default update all fields. + """ + + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1alpha.SampleQuerySet] + 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/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py index 450901aa5f10..b3b748cc415f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py @@ -33,6 +33,10 @@ ) from .services.document_service import DocumentServiceAsyncClient, DocumentServiceClient from .services.engine_service import EngineServiceAsyncClient, EngineServiceClient +from .services.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, +) from .services.grounded_generation_service import ( GroundedGenerationServiceAsyncClient, GroundedGenerationServiceClient, @@ -43,6 +47,14 @@ RecommendationServiceAsyncClient, RecommendationServiceClient, ) +from .services.sample_query_service import ( + SampleQueryServiceAsyncClient, + SampleQueryServiceClient, +) +from .services.sample_query_set_service import ( + SampleQuerySetServiceAsyncClient, + SampleQuerySetServiceClient, +) from .services.schema_service import SchemaServiceAsyncClient, SchemaServiceClient from .services.search_service import SearchServiceAsyncClient, SearchServiceClient from .services.search_tuning_service import ( @@ -62,6 +74,7 @@ UserEventServiceClient, ) from .types.answer import Answer +from .types.chunk import Chunk from .types.common import ( CustomAttribute, DoubleList, @@ -149,6 +162,16 @@ TuneEngineResponse, UpdateEngineRequest, ) +from .types.evaluation import Evaluation, QualityMetrics +from .types.evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) from .types.grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, @@ -167,6 +190,9 @@ ImportDocumentsRequest, ImportDocumentsResponse, ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, ImportSuggestionDenyListEntriesMetadata, ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, @@ -187,6 +213,24 @@ ) from .types.rank_service import RankingRecord, RankRequest, RankResponse from .types.recommendation_service import RecommendRequest, RecommendResponse +from .types.sample_query import SampleQuery +from .types.sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from .types.sample_query_set import SampleQuerySet +from .types.sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) from .types.schema import Schema from .types.schema_service import ( CreateSchemaMetadata, @@ -264,10 +308,13 @@ "DataStoreServiceAsyncClient", "DocumentServiceAsyncClient", "EngineServiceAsyncClient", + "EvaluationServiceAsyncClient", "GroundedGenerationServiceAsyncClient", "ProjectServiceAsyncClient", "RankServiceAsyncClient", "RecommendationServiceAsyncClient", + "SampleQueryServiceAsyncClient", + "SampleQuerySetServiceAsyncClient", "SchemaServiceAsyncClient", "SearchServiceAsyncClient", "SearchTuningServiceAsyncClient", @@ -289,6 +336,7 @@ "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", + "Chunk", "CloudSqlSource", "CollectUserEventRequest", "CompleteQueryRequest", @@ -311,6 +359,10 @@ "CreateDocumentRequest", "CreateEngineMetadata", "CreateEngineRequest", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "CreateSampleQueryRequest", + "CreateSampleQuerySetRequest", "CreateSchemaMetadata", "CreateSchemaRequest", "CreateSessionRequest", @@ -327,6 +379,8 @@ "DeleteDocumentRequest", "DeleteEngineMetadata", "DeleteEngineRequest", + "DeleteSampleQueryRequest", + "DeleteSampleQuerySetRequest", "DeleteSchemaMetadata", "DeleteSchemaRequest", "DeleteSessionRequest", @@ -346,6 +400,8 @@ "EnableAdvancedSiteSearchResponse", "Engine", "EngineServiceClient", + "Evaluation", + "EvaluationServiceClient", "FactChunk", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", @@ -358,6 +414,9 @@ "GetDataStoreRequest", "GetDocumentRequest", "GetEngineRequest", + "GetEvaluationRequest", + "GetSampleQueryRequest", + "GetSampleQuerySetRequest", "GetSchemaRequest", "GetServingConfigRequest", "GetSessionRequest", @@ -369,6 +428,9 @@ "ImportDocumentsRequest", "ImportDocumentsResponse", "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", "ImportSuggestionDenyListEntriesMetadata", "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", @@ -389,6 +451,14 @@ "ListDocumentsResponse", "ListEnginesRequest", "ListEnginesResponse", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", "ListSchemasRequest", "ListSchemasResponse", "ListServingConfigsRequest", @@ -411,6 +481,7 @@ "PurgeSuggestionDenyListEntriesMetadata", "PurgeSuggestionDenyListEntriesRequest", "PurgeSuggestionDenyListEntriesResponse", + "QualityMetrics", "Query", "RankRequest", "RankResponse", @@ -424,6 +495,10 @@ "RecrawlUrisResponse", "Reply", "ResumeEngineRequest", + "SampleQuery", + "SampleQueryServiceClient", + "SampleQuerySet", + "SampleQuerySetServiceClient", "Schema", "SchemaServiceClient", "SearchAddOn", @@ -457,6 +532,8 @@ "UpdateDataStoreRequest", "UpdateDocumentRequest", "UpdateEngineRequest", + "UpdateSampleQueryRequest", + "UpdateSampleQuerySetRequest", "UpdateSchemaMetadata", "UpdateSchemaRequest", "UpdateServingConfigRequest", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json index d039c25b28ac..17a71015f1fa 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json @@ -734,6 +734,85 @@ } } }, + "EvaluationService": { + "clients": { + "grpc": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EvaluationServiceAsyncClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + }, + "rest": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + } + } + } + } + }, "GroundedGenerationService": { "clients": { "grpc": { @@ -870,6 +949,209 @@ } } }, + "SampleQueryService": { + "clients": { + "grpc": { + "libraryClient": "SampleQueryServiceClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SampleQueryServiceAsyncClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + }, + "rest": { + "libraryClient": "SampleQueryServiceClient", + "rpcs": { + "CreateSampleQuery": { + "methods": [ + "create_sample_query" + ] + }, + "DeleteSampleQuery": { + "methods": [ + "delete_sample_query" + ] + }, + "GetSampleQuery": { + "methods": [ + "get_sample_query" + ] + }, + "ImportSampleQueries": { + "methods": [ + "import_sample_queries" + ] + }, + "ListSampleQueries": { + "methods": [ + "list_sample_queries" + ] + }, + "UpdateSampleQuery": { + "methods": [ + "update_sample_query" + ] + } + } + } + } + }, + "SampleQuerySetService": { + "clients": { + "grpc": { + "libraryClient": "SampleQuerySetServiceClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SampleQuerySetServiceAsyncClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + }, + "rest": { + "libraryClient": "SampleQuerySetServiceClient", + "rpcs": { + "CreateSampleQuerySet": { + "methods": [ + "create_sample_query_set" + ] + }, + "DeleteSampleQuerySet": { + "methods": [ + "delete_sample_query_set" + ] + }, + "GetSampleQuerySet": { + "methods": [ + "get_sample_query_set" + ] + }, + "ListSampleQuerySets": { + "methods": [ + "list_sample_query_sets" + ] + }, + "UpdateSampleQuerySet": { + "methods": [ + "update_sample_query_set" + ] + } + } + } + } + }, "SchemaService": { "clients": { "grpc": { diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py index 9d5fd39a4c03..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.14" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py index 18cca7b93783..7e2cdd966469 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py @@ -415,10 +415,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -988,10 +996,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py index 19d3418393d6..5d5c930da7d8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py @@ -1053,10 +1053,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py index 02be7eb7984d..2eb0d038f30a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py @@ -2204,10 +2204,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py index 2336b25a04d0..aedd3117f509 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py @@ -473,10 +473,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -1244,10 +1252,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py index 82f8b1f97d94..db93f79c1cf2 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py @@ -523,10 +523,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -1486,10 +1494,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py index c2b45b15493f..8d4d7c4c1f15 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py @@ -557,10 +557,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -1603,10 +1611,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/__init__.py new file mode 100644 index 000000000000..a84af6a63a20 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import EvaluationServiceAsyncClient +from .client import EvaluationServiceClient + +__all__ = ( + "EvaluationServiceClient", + "EvaluationServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/async_client.py new file mode 100644 index 000000000000..405f7a3c4164 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/async_client.py @@ -0,0 +1,1002 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.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 timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.evaluation_service import pagers +from google.cloud.discoveryengine_v1beta.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1beta.types import evaluation +from google.cloud.discoveryengine_v1beta.types import evaluation_service + +from .client import EvaluationServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport + + +class EvaluationServiceAsyncClient: + """Service for managing + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s, + """ + + _client: EvaluationServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EvaluationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EvaluationServiceClient._DEFAULT_UNIVERSE + + branch_path = staticmethod(EvaluationServiceClient.branch_path) + parse_branch_path = staticmethod(EvaluationServiceClient.parse_branch_path) + data_store_path = staticmethod(EvaluationServiceClient.data_store_path) + parse_data_store_path = staticmethod(EvaluationServiceClient.parse_data_store_path) + evaluation_path = staticmethod(EvaluationServiceClient.evaluation_path) + parse_evaluation_path = staticmethod(EvaluationServiceClient.parse_evaluation_path) + location_path = staticmethod(EvaluationServiceClient.location_path) + parse_location_path = staticmethod(EvaluationServiceClient.parse_location_path) + sample_query_path = staticmethod(EvaluationServiceClient.sample_query_path) + parse_sample_query_path = staticmethod( + EvaluationServiceClient.parse_sample_query_path + ) + sample_query_set_path = staticmethod(EvaluationServiceClient.sample_query_set_path) + parse_sample_query_set_path = staticmethod( + EvaluationServiceClient.parse_sample_query_set_path + ) + serving_config_path = staticmethod(EvaluationServiceClient.serving_config_path) + parse_serving_config_path = staticmethod( + EvaluationServiceClient.parse_serving_config_path + ) + common_billing_account_path = staticmethod( + EvaluationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EvaluationServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(EvaluationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + EvaluationServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + EvaluationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + EvaluationServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(EvaluationServiceClient.common_project_path) + parse_common_project_path = staticmethod( + EvaluationServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(EvaluationServiceClient.common_location_path) + parse_common_location_path = staticmethod( + EvaluationServiceClient.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: + EvaluationServiceAsyncClient: The constructed client. + """ + return EvaluationServiceClient.from_service_account_info.__func__(EvaluationServiceAsyncClient, 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: + EvaluationServiceAsyncClient: The constructed client. + """ + return EvaluationServiceClient.from_service_account_file.__func__(EvaluationServiceAsyncClient, 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 EvaluationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(EvaluationServiceClient).get_transport_class, type(EvaluationServiceClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EvaluationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation] + method. + name (:class:`str`): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, 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.ListEvaluationsAsyncPager: + r"""Gets a list of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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_evaluations(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListEvaluationsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + parent (:class:`str`): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s + under this location, regardless of whether or not this + location 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.evaluation_service.pagers.ListEvaluationsAsyncPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcd_evaluation.Evaluation] = 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 + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1beta.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(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.CreateEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (:class:`google.cloud.discoveryengine_v1beta.types.Evaluation`): + Required. The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + to create. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.Evaluation` An evaluation is a single execution (or run) of an evaluation process. It + encapsulates the state of the evaluation and the + resulting 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, evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_evaluation.Evaluation, + metadata_type=evaluation_service.CreateEvaluationMetadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + evaluation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationResultsAsyncPager: + r"""Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation_results(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + evaluation (:class:`str`): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless + of whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + 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([evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_results + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation", request.evaluation),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationResultsAsyncPager( + 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "EvaluationServiceAsyncClient": + 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__ = ("EvaluationServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/client.py new file mode 100644 index 000000000000..ed8115f3326a --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/client.py @@ -0,0 +1,1535 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.evaluation_service import pagers +from google.cloud.discoveryengine_v1beta.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1beta.types import evaluation +from google.cloud.discoveryengine_v1beta.types import evaluation_service + +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc import EvaluationServiceGrpcTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .transports.rest import EvaluationServiceRestTransport + + +class EvaluationServiceClientMeta(type): + """Metaclass for the EvaluationService 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[EvaluationServiceTransport]] + _transport_registry["grpc"] = EvaluationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EvaluationServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EvaluationServiceTransport]: + """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 EvaluationServiceClient(metaclass=EvaluationServiceClientMeta): + """Service for managing + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceClient: 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: + EvaluationServiceClient: 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) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: 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 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 evaluation_path( + project: str, + location: str, + evaluation: str, + ) -> str: + """Returns a fully-qualified evaluation string.""" + return ( + "projects/{project}/locations/{location}/evaluations/{evaluation}".format( + project=project, + location=location, + evaluation=evaluation, + ) + ) + + @staticmethod + def parse_evaluation_path(path: str) -> Dict[str, str]: + """Parses a evaluation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/evaluations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def 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_location_path(path: str) -> Dict[str, str]: + """Parses a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_path( + project: str, + location: str, + sample_query_set: str, + sample_query: str, + ) -> str: + """Returns a fully-qualified sample_query string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + + @staticmethod + def parse_sample_query_path(path: str) -> Dict[str, str]: + """Parses a sample_query path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)/sampleQueries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?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 + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = EvaluationServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or EvaluationServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = EvaluationServiceClient._read_environment_variables() + self._client_cert_source = EvaluationServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = EvaluationServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, EvaluationServiceTransport) + if transport_provided: + # transport is a EvaluationServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(EvaluationServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or EvaluationServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[EvaluationServiceTransport], + Callable[..., EvaluationServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EvaluationServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Gets a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation] + method. + name (str): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + 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.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, 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.ListEvaluationsPager: + r"""Gets a list of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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_evaluations(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListEvaluationsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s + under this location, regardless of whether or not this + location 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.evaluation_service.pagers.ListEvaluationsPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(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_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcd_evaluation.Evaluation] = 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 + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1beta.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (google.cloud.discoveryengine_v1beta.types.Evaluation): + Required. The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + to create. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.Evaluation` An evaluation is a single execution (or run) of an evaluation process. It + encapsulates the state of the evaluation and the + resulting 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, evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_evaluation.Evaluation, + metadata_type=evaluation_service.CreateEvaluationMetadata, + ) + + # Done; return the response. + return response + + def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + evaluation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationResultsPager: + r"""Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_evaluation_results(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + evaluation (str): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless + of whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.evaluation_service.pagers.ListEvaluationResultsPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + 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([evaluation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation", request.evaluation),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EvaluationServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("EvaluationServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/pagers.py new file mode 100644 index 000000000000..26239d36b0e2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/pagers.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1beta.types import evaluation, evaluation_service + + +class ListEvaluationsPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse` + 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[..., evaluation_service.ListEvaluationsResponse], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + 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.ListEvaluationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse): + 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 = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationsResponse]: + 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[evaluation.Evaluation]: + for page in self.pages: + yield from page.evaluations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationsAsyncPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse` + 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[evaluation_service.ListEvaluationsResponse]], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + 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.ListEvaluationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListEvaluationsResponse): + 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 = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[evaluation_service.ListEvaluationsResponse]: + 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[evaluation.Evaluation]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse` + 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[..., evaluation_service.ListEvaluationResultsResponse], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + 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.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse): + 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 = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationResultsResponse]: + 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[evaluation_service.ListEvaluationResultsResponse.EvaluationResult]: + for page in self.pages: + yield from page.evaluation_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsAsyncPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse` + 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[evaluation_service.ListEvaluationResultsResponse] + ], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + 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.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse): + 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 = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationResultsResponse]: + 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[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/__init__.py new file mode 100644 index 000000000000..992af2ba4c25 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport +from .grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .rest import EvaluationServiceRestInterceptor, EvaluationServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EvaluationServiceTransport]] +_transport_registry["grpc"] = EvaluationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EvaluationServiceRestTransport + +__all__ = ( + "EvaluationServiceTransport", + "EvaluationServiceGrpcTransport", + "EvaluationServiceGrpcAsyncIOTransport", + "EvaluationServiceRestTransport", + "EvaluationServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/base.py new file mode 100644 index 000000000000..5964805f0aa9 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/base.py @@ -0,0 +1,243 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import evaluation, evaluation_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class EvaluationServiceTransport(abc.ABC): + """Abstract transport class for EvaluationService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_evaluation: gapic_v1.method.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: gapic_v1.method.wrap_method( + self.create_evaluation, + default_timeout=300.0, + client_info=client_info, + ), + self.list_evaluation_results: gapic_v1.method.wrap_method( + self.list_evaluation_results, + 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_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], + Union[evaluation.Evaluation, Awaitable[evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Union[ + evaluation_service.ListEvaluationsResponse, + Awaitable[evaluation_service.ListEvaluationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Union[ + evaluation_service.ListEvaluationResultsResponse, + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("EvaluationServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc.py new file mode 100644 index 000000000000..a63b3a0779fc --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc.py @@ -0,0 +1,435 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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_v1beta.types import evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport + + +class EvaluationServiceGrpcTransport(EvaluationServiceTransport): + """gRPC backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Returns: + Callable[[~.GetEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Gets a list of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s. + + Returns: + Callable[[~.ListEvaluationsRequest], + ~.ListEvaluationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + Returns: + Callable[[~.CreateEvaluationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_evaluation"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + ~.ListEvaluationResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("EvaluationServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9e82abf728c9 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/grpc_asyncio.py @@ -0,0 +1,465 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport + + +class EvaluationServiceGrpcAsyncIOTransport(EvaluationServiceTransport): + """gRPC AsyncIO backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._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_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], Awaitable[evaluation.Evaluation] + ]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Returns: + Callable[[~.GetEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Awaitable[evaluation_service.ListEvaluationsResponse], + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Gets a list of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s. + + Returns: + Callable[[~.ListEvaluationsRequest], + Awaitable[~.ListEvaluationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Upon creation, the evaluation will be automatically triggered + and begin execution. + + Returns: + Callable[[~.CreateEvaluationRequest], + 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_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_evaluation"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Gets a list of results for a given a + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + Awaitable[~.ListEvaluationResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_evaluation: gapic_v1.method_async.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method_async.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: gapic_v1.method_async.wrap_method( + self.create_evaluation, + default_timeout=300.0, + client_info=client_info, + ), + self.list_evaluation_results: gapic_v1.method_async.wrap_method( + self.list_evaluation_results, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("EvaluationServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py new file mode 100644 index 000000000000..b6d1304d9439 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py @@ -0,0 +1,1271 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import 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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.types import evaluation, evaluation_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import EvaluationServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class EvaluationServiceRestInterceptor: + """Interceptor for EvaluationService. + + 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 EvaluationServiceRestTransport. + + .. code-block:: python + class MyCustomEvaluationServiceInterceptor(EvaluationServiceRestInterceptor): + def pre_create_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_results(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_results(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EvaluationServiceRestTransport(interceptor=MyCustomEvaluationServiceInterceptor()) + client = EvaluationServiceClient(transport=transport) + + + """ + + def pre_create_evaluation( + self, + request: evaluation_service.CreateEvaluationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.CreateEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_evaluation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_evaluation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_get_evaluation( + self, + request: evaluation_service.GetEvaluationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.GetEvaluationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation( + self, response: evaluation.Evaluation + ) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_evaluation_results( + self, + request: evaluation_service.ListEvaluationResultsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + evaluation_service.ListEvaluationResultsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_evaluation_results + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_results( + self, response: evaluation_service.ListEvaluationResultsResponse + ) -> evaluation_service.ListEvaluationResultsResponse: + """Post-rpc interceptor for list_evaluation_results + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_evaluations( + self, + request: evaluation_service.ListEvaluationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[evaluation_service.ListEvaluationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluations( + self, response: evaluation_service.ListEvaluationsResponse + ) -> evaluation_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService 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 EvaluationService 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 EvaluationService 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 EvaluationService 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 EvaluationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EvaluationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EvaluationServiceRestInterceptor + + +class EvaluationServiceRestTransport(EvaluationServiceTransport): + """REST backend transport for EvaluationService. + + Service for managing + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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[EvaluationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 EvaluationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "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 _CreateEvaluation(EvaluationServiceRestStub): + def __hash__(self): + return hash("CreateEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.CreateEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create evaluation method over HTTP. + + Args: + request (~.evaluation_service.CreateEvaluationRequest): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The 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/*}/evaluations", + "body": "evaluation", + }, + ] + request, metadata = self._interceptor.pre_create_evaluation( + request, metadata + ) + pb_request = evaluation_service.CreateEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_evaluation(resp) + return resp + + class _GetEvaluation(EvaluationServiceRestStub): + def __hash__(self): + return hash("GetEvaluation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.GetEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationRequest): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation.Evaluation: + An evaluation is a single execution + (or run) of an evaluation process. It + encapsulates the state of the evaluation + and the resulting data. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + pb_request = evaluation_service.GetEvaluationRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_evaluation(resp) + return resp + + class _ListEvaluationResults(EvaluationServiceRestStub): + def __hash__(self): + return hash("ListEvaluationResults") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.ListEvaluationResultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_service.ListEvaluationResultsResponse: + r"""Call the list evaluation results method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationResultsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation_service.ListEvaluationResultsResponse: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{evaluation=projects/*/locations/*/evaluations/*}:listResults", + }, + ] + request, metadata = self._interceptor.pre_list_evaluation_results( + request, metadata + ) + pb_request = evaluation_service.ListEvaluationResultsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation_service.ListEvaluationResultsResponse() + pb_resp = evaluation_service.ListEvaluationResultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluation_results(resp) + return resp + + class _ListEvaluations(EvaluationServiceRestStub): + def __hash__(self): + return hash("ListEvaluations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: evaluation_service.ListEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationsRequest): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.evaluation_service.ListEvaluationsResponse: + Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/evaluations", + }, + ] + request, metadata = self._interceptor.pre_list_evaluations( + request, metadata + ) + pb_request = evaluation_service.ListEvaluationsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = evaluation_service.ListEvaluationsResponse() + pb_resp = evaluation_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_evaluations(resp) + return resp + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], 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._CreateEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationResults(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(EvaluationServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(EvaluationServiceRestStub): + 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/*/dataConnector/operations/*}", + }, + { + "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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/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(EvaluationServiceRestStub): + 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/*/dataConnector}/operations", + }, + { + "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__ = ("EvaluationServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py index 0d9dc3f49f17..2902ee059c31 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py @@ -524,10 +524,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py index 4b66b216811c..c0d43ee2545c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py @@ -346,10 +346,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -683,10 +691,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py index 34d6325b6e9d..6e2bea21bc97 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py @@ -515,10 +515,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py index ddd153633b6b..6ea66e5264a8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py @@ -529,10 +529,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/__init__.py new file mode 100644 index 000000000000..41a401cc78de --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SampleQueryServiceAsyncClient +from .client import SampleQueryServiceClient + +__all__ = ( + "SampleQueryServiceClient", + "SampleQueryServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/async_client.py new file mode 100644 index 000000000000..57846d86667c --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/async_client.py @@ -0,0 +1,1231 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.sample_query_service import pagers +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +from .client import SampleQueryServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .transports.grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport + + +class SampleQueryServiceAsyncClient: + """Service for managing + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s, + """ + + _client: SampleQueryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SampleQueryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SampleQueryServiceClient._DEFAULT_UNIVERSE + + sample_query_path = staticmethod(SampleQueryServiceClient.sample_query_path) + parse_sample_query_path = staticmethod( + SampleQueryServiceClient.parse_sample_query_path + ) + sample_query_set_path = staticmethod(SampleQueryServiceClient.sample_query_set_path) + parse_sample_query_set_path = staticmethod( + SampleQueryServiceClient.parse_sample_query_set_path + ) + common_billing_account_path = staticmethod( + SampleQueryServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SampleQueryServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SampleQueryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SampleQueryServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SampleQueryServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SampleQueryServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SampleQueryServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SampleQueryServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SampleQueryServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SampleQueryServiceClient.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: + SampleQueryServiceAsyncClient: The constructed client. + """ + return SampleQueryServiceClient.from_service_account_info.__func__(SampleQueryServiceAsyncClient, 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: + SampleQueryServiceAsyncClient: The constructed client. + """ + return SampleQueryServiceClient.from_service_account_file.__func__(SampleQueryServiceAsyncClient, 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 SampleQueryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SampleQueryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQueryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(SampleQueryServiceClient).get_transport_class, + type(SampleQueryServiceClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQueryServiceTransport, + Callable[..., SampleQueryServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQueryServiceTransport,Callable[..., SampleQueryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQueryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SampleQueryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_sample_query( + self, + request: Optional[ + Union[sample_query_service.GetSampleQueryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Gets a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.GetSampleQueryRequest): + request = sample_query_service.GetSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sample_queries( + self, + request: Optional[ + Union[sample_query_service.ListSampleQueriesRequest, 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.ListSampleQueriesAsyncPager: + r"""Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest, dict]]): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + parent (:class:`str`): + Required. The parent sample query set resource name, + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or + not this sample query set 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers.ListSampleQueriesAsyncPager: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.ListSampleQueriesRequest): + request = sample_query_service.ListSampleQueriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sample_queries + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSampleQueriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sample_query( + self, + request: Optional[ + Union[sample_query_service.CreateSampleQueryRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query: Optional[gcd_sample_query.SampleQuery] = None, + sample_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Creates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = await client.create_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query (:class:`google.cloud.discoveryengine_v1beta.types.SampleQuery`): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to create. + + This corresponds to the ``sample_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_id (:class:`str`): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1beta.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQueryRequest.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 ``sample_query_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query, sample_query_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.CreateSampleQueryRequest): + request = sample_query_service.CreateSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query is not None: + request.sample_query = sample_query + if sample_query_id is not None: + request.sample_query_id = sample_query_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_sample_query( + self, + request: Optional[ + Union[sample_query_service.UpdateSampleQueryRequest, dict] + ] = None, + *, + sample_query: Optional[gcd_sample_query.SampleQuery] = 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_sample_query.SampleQuery: + r"""Updates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = await client.update_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery] + method. + sample_query (:class:`google.cloud.discoveryengine_v1beta.types.SampleQuery`): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query`` 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 imported 'simple query' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.UpdateSampleQueryRequest): + request = sample_query_service.UpdateSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query is not None: + request.sample_query = sample_query + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query.name", request.sample_query.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sample_query( + self, + request: Optional[ + Union[sample_query_service.DeleteSampleQueryRequest, dict] + ] = 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 + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest, dict]]): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.DeleteSampleQueryRequest): + request = sample_query_service.DeleteSampleQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sample_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_sample_queries( + self, + request: Optional[Union[import_config.ImportSampleQueriesRequest, 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 + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to be successfully imported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1beta.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(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.ImportSampleQueriesRequest, dict]]): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + 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.ImportSampleQueriesResponse` Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportSampleQueriesRequest): + request = import_config.ImportSampleQueriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_sample_queries + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportSampleQueriesResponse, + metadata_type=import_config.ImportSampleQueriesMetadata, + ) + + # 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SampleQueryServiceAsyncClient": + 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__ = ("SampleQueryServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/client.py new file mode 100644 index 000000000000..3ff8049c09ac --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/client.py @@ -0,0 +1,1659 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 google.cloud.discoveryengine_v1beta.services.sample_query_service import pagers +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +from .transports.base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .transports.grpc import SampleQueryServiceGrpcTransport +from .transports.grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport +from .transports.rest import SampleQueryServiceRestTransport + + +class SampleQueryServiceClientMeta(type): + """Metaclass for the SampleQueryService 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[SampleQueryServiceTransport]] + _transport_registry["grpc"] = SampleQueryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SampleQueryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SampleQueryServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SampleQueryServiceTransport]: + """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 SampleQueryServiceClient(metaclass=SampleQueryServiceClientMeta): + """Service for managing + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SampleQueryServiceClient: 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: + SampleQueryServiceClient: 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) -> SampleQueryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQueryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def sample_query_path( + project: str, + location: str, + sample_query_set: str, + sample_query: str, + ) -> str: + """Returns a fully-qualified sample_query string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + + @staticmethod + def parse_sample_query_path(path: str) -> Dict[str, str]: + """Parses a sample_query path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)/sampleQueries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SampleQueryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or SampleQueryServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQueryServiceTransport, + Callable[..., SampleQueryServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQueryServiceTransport,Callable[..., SampleQueryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQueryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SampleQueryServiceClient._read_environment_variables() + self._client_cert_source = SampleQueryServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SampleQueryServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SampleQueryServiceTransport) + if transport_provided: + # transport is a SampleQueryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SampleQueryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SampleQueryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SampleQueryServiceTransport], + Callable[..., SampleQueryServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SampleQueryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_sample_query( + self, + request: Optional[ + Union[sample_query_service.GetSampleQueryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Gets a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery] + method. + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.GetSampleQueryRequest): + request = sample_query_service.GetSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sample_queries( + self, + request: Optional[ + Union[sample_query_service.ListSampleQueriesRequest, 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.ListSampleQueriesPager: + r"""Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest, dict]): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + parent (str): + Required. The parent sample query set resource name, + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or + not this sample query set 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.sample_query_service.pagers.ListSampleQueriesPager: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.ListSampleQueriesRequest): + request = sample_query_service.ListSampleQueriesRequest(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_sample_queries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSampleQueriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sample_query( + self, + request: Optional[ + Union[sample_query_service.CreateSampleQueryRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query: Optional[gcd_sample_query.SampleQuery] = None, + sample_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Creates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = client.create_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to create. + + This corresponds to the ``sample_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_id (str): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1beta.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQueryRequest.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 ``sample_query_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.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query, sample_query_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.CreateSampleQueryRequest): + request = sample_query_service.CreateSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query is not None: + request.sample_query = sample_query + if sample_query_id is not None: + request.sample_query_id = sample_query_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_sample_query( + self, + request: Optional[ + Union[sample_query_service.UpdateSampleQueryRequest, dict] + ] = None, + *, + sample_query: Optional[gcd_sample_query.SampleQuery] = 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_sample_query.SampleQuery: + r"""Updates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = client.update_sample_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery] + method. + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query`` 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 imported 'simple query' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.UpdateSampleQueryRequest): + request = sample_query_service.UpdateSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query is not None: + request.sample_query = sample_query + 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query.name", request.sample_query.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sample_query( + self, + request: Optional[ + Union[sample_query_service.DeleteSampleQueryRequest, dict] + ] = 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 + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest, dict]): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery] + method. + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_service.DeleteSampleQueryRequest): + request = sample_query_service.DeleteSampleQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_sample_queries( + self, + request: Optional[Union[import_config.ImportSampleQueriesRequest, 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 + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to be successfully imported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1beta.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest, dict]): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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.ImportSampleQueriesResponse` Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportSampleQueriesRequest): + request = import_config.ImportSampleQueriesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_sample_queries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportSampleQueriesResponse, + metadata_type=import_config.ImportSampleQueriesMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SampleQueryServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SampleQueryServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/pagers.py new file mode 100644 index 000000000000..4bbb209ea167 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/pagers.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1beta.types import sample_query, sample_query_service + + +class ListSampleQueriesPager: + """A pager for iterating through ``list_sample_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sample_queries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSampleQueries`` requests and continue to iterate + through the ``sample_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse` + 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[..., sample_query_service.ListSampleQueriesResponse], + request: sample_query_service.ListSampleQueriesRequest, + response: sample_query_service.ListSampleQueriesResponse, + *, + 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.ListSampleQueriesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse): + 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 = sample_query_service.ListSampleQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[sample_query_service.ListSampleQueriesResponse]: + 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[sample_query.SampleQuery]: + for page in self.pages: + yield from page.sample_queries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSampleQueriesAsyncPager: + """A pager for iterating through ``list_sample_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sample_queries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSampleQueries`` requests and continue to iterate + through the ``sample_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse` + 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[sample_query_service.ListSampleQueriesResponse] + ], + request: sample_query_service.ListSampleQueriesRequest, + response: sample_query_service.ListSampleQueriesResponse, + *, + 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.ListSampleQueriesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSampleQueriesResponse): + 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 = sample_query_service.ListSampleQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[sample_query_service.ListSampleQueriesResponse]: + 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[sample_query.SampleQuery]: + async def async_generator(): + async for page in self.pages: + for response in page.sample_queries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/__init__.py new file mode 100644 index 000000000000..115e91897ac1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SampleQueryServiceTransport +from .grpc import SampleQueryServiceGrpcTransport +from .grpc_asyncio import SampleQueryServiceGrpcAsyncIOTransport +from .rest import SampleQueryServiceRestInterceptor, SampleQueryServiceRestTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SampleQueryServiceTransport]] +_transport_registry["grpc"] = SampleQueryServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SampleQueryServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SampleQueryServiceRestTransport + +__all__ = ( + "SampleQueryServiceTransport", + "SampleQueryServiceGrpcTransport", + "SampleQueryServiceGrpcAsyncIOTransport", + "SampleQueryServiceRestTransport", + "SampleQueryServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/base.py new file mode 100644 index 000000000000..ff9eefb8c6ef --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/base.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SampleQueryServiceTransport(abc.ABC): + """Abstract transport class for SampleQueryService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_sample_query: gapic_v1.method.wrap_method( + self.get_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_queries: gapic_v1.method.wrap_method( + self.list_sample_queries, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query: gapic_v1.method.wrap_method( + self.create_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query: gapic_v1.method.wrap_method( + self.update_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query: gapic_v1.method.wrap_method( + self.delete_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.import_sample_queries: gapic_v1.method.wrap_method( + self.import_sample_queries, + 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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], + Union[sample_query.SampleQuery, Awaitable[sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + Union[ + sample_query_service.ListSampleQueriesResponse, + Awaitable[sample_query_service.ListSampleQueriesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], + Union[gcd_sample_query.SampleQuery, Awaitable[gcd_sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], + Union[gcd_sample_query.SampleQuery, Awaitable[gcd_sample_query.SampleQuery]], + ]: + raise NotImplementedError() + + @property + def delete_sample_query( + self, + ) -> Callable[ + [sample_query_service.DeleteSampleQueryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def import_sample_queries( + self, + ) -> Callable[ + [import_config.ImportSampleQueriesRequest], + 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 cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SampleQueryServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc.py new file mode 100644 index 000000000000..3df6b7980da1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc.py @@ -0,0 +1,496 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport + + +class SampleQueryServiceGrpcTransport(SampleQueryServiceTransport): + """gRPC backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], sample_query.SampleQuery + ]: + r"""Return a callable for the get sample query method over gRPC. + + Gets a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.GetSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query" not in self._stubs: + self._stubs["get_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/GetSampleQuery", + request_serializer=sample_query_service.GetSampleQueryRequest.serialize, + response_deserializer=sample_query.SampleQuery.deserialize, + ) + return self._stubs["get_sample_query"] + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + sample_query_service.ListSampleQueriesResponse, + ]: + r"""Return a callable for the list sample queries method over gRPC. + + Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + + Returns: + Callable[[~.ListSampleQueriesRequest], + ~.ListSampleQueriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["list_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/ListSampleQueries", + request_serializer=sample_query_service.ListSampleQueriesRequest.serialize, + response_deserializer=sample_query_service.ListSampleQueriesResponse.deserialize, + ) + return self._stubs["list_sample_queries"] + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + r"""Return a callable for the create sample query method over gRPC. + + Creates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + + Returns: + Callable[[~.CreateSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["create_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/CreateSampleQuery", + request_serializer=sample_query_service.CreateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["create_sample_query"] + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + r"""Return a callable for the update sample query method over gRPC. + + Updates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.UpdateSampleQueryRequest], + ~.SampleQuery]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["update_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/UpdateSampleQuery", + request_serializer=sample_query_service.UpdateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["update_sample_query"] + + @property + def delete_sample_query( + self, + ) -> Callable[[sample_query_service.DeleteSampleQueryRequest], empty_pb2.Empty]: + r"""Return a callable for the delete sample query method over gRPC. + + Deletes a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.DeleteSampleQueryRequest], + ~.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_sample_query" not in self._stubs: + self._stubs["delete_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/DeleteSampleQuery", + request_serializer=sample_query_service.DeleteSampleQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query"] + + @property + def import_sample_queries( + self, + ) -> Callable[[import_config.ImportSampleQueriesRequest], operations_pb2.Operation]: + r"""Return a callable for the import sample queries method over gRPC. + + Bulk import of multiple + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to be successfully imported. + + Returns: + Callable[[~.ImportSampleQueriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["import_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/ImportSampleQueries", + request_serializer=import_config.ImportSampleQueriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_sample_queries"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SampleQueryServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..77adb02926df --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/grpc_asyncio.py @@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO, SampleQueryServiceTransport +from .grpc import SampleQueryServiceGrpcTransport + + +class SampleQueryServiceGrpcAsyncIOTransport(SampleQueryServiceTransport): + """gRPC AsyncIO backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._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_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], + Awaitable[sample_query.SampleQuery], + ]: + r"""Return a callable for the get sample query method over gRPC. + + Gets a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.GetSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query" not in self._stubs: + self._stubs["get_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/GetSampleQuery", + request_serializer=sample_query_service.GetSampleQueryRequest.serialize, + response_deserializer=sample_query.SampleQuery.deserialize, + ) + return self._stubs["get_sample_query"] + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + Awaitable[sample_query_service.ListSampleQueriesResponse], + ]: + r"""Return a callable for the list sample queries method over gRPC. + + Gets a list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + + Returns: + Callable[[~.ListSampleQueriesRequest], + Awaitable[~.ListSampleQueriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_queries" not in self._stubs: + self._stubs["list_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/ListSampleQueries", + request_serializer=sample_query_service.ListSampleQueriesRequest.serialize, + response_deserializer=sample_query_service.ListSampleQueriesResponse.deserialize, + ) + return self._stubs["list_sample_queries"] + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], + Awaitable[gcd_sample_query.SampleQuery], + ]: + r"""Return a callable for the create sample query method over gRPC. + + Creates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + + Returns: + Callable[[~.CreateSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["create_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/CreateSampleQuery", + request_serializer=sample_query_service.CreateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["create_sample_query"] + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], + Awaitable[gcd_sample_query.SampleQuery], + ]: + r"""Return a callable for the update sample query method over gRPC. + + Updates a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.UpdateSampleQueryRequest], + Awaitable[~.SampleQuery]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query" not in self._stubs: + self._stubs["update_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/UpdateSampleQuery", + request_serializer=sample_query_service.UpdateSampleQueryRequest.serialize, + response_deserializer=gcd_sample_query.SampleQuery.deserialize, + ) + return self._stubs["update_sample_query"] + + @property + def delete_sample_query( + self, + ) -> Callable[ + [sample_query_service.DeleteSampleQueryRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete sample query method over gRPC. + + Deletes a + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Returns: + Callable[[~.DeleteSampleQueryRequest], + 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_sample_query" not in self._stubs: + self._stubs["delete_sample_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/DeleteSampleQuery", + request_serializer=sample_query_service.DeleteSampleQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query"] + + @property + def import_sample_queries( + self, + ) -> Callable[ + [import_config.ImportSampleQueriesRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the import sample queries method over gRPC. + + Bulk import of multiple + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + Sample queries that already exist may be deleted. + + Note: It is possible for a subset of the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to be successfully imported. + + Returns: + Callable[[~.ImportSampleQueriesRequest], + 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_sample_queries" not in self._stubs: + self._stubs["import_sample_queries"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQueryService/ImportSampleQueries", + request_serializer=import_config.ImportSampleQueriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_sample_queries"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_sample_query: gapic_v1.method_async.wrap_method( + self.get_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_queries: gapic_v1.method_async.wrap_method( + self.list_sample_queries, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query: gapic_v1.method_async.wrap_method( + self.create_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query: gapic_v1.method_async.wrap_method( + self.update_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query: gapic_v1.method_async.wrap_method( + self.delete_sample_query, + default_timeout=None, + client_info=client_info, + ), + self.import_sample_queries: gapic_v1.method_async.wrap_method( + self.import_sample_queries, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SampleQueryServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py new file mode 100644 index 000000000000..9d538cafce94 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py @@ -0,0 +1,1528 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import 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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SampleQueryServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SampleQueryServiceRestInterceptor: + """Interceptor for SampleQueryService. + + 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 SampleQueryServiceRestTransport. + + .. code-block:: python + class MyCustomSampleQueryServiceInterceptor(SampleQueryServiceRestInterceptor): + def pre_create_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_sample_queries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_sample_queries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sample_queries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sample_queries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sample_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sample_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SampleQueryServiceRestTransport(interceptor=MyCustomSampleQueryServiceInterceptor()) + client = SampleQueryServiceClient(transport=transport) + + + """ + + def pre_create_sample_query( + self, + request: sample_query_service.CreateSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.CreateSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_create_sample_query( + self, response: gcd_sample_query.SampleQuery + ) -> gcd_sample_query.SampleQuery: + """Post-rpc interceptor for create_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_delete_sample_query( + self, + request: sample_query_service.DeleteSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.DeleteSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def pre_get_sample_query( + self, + request: sample_query_service.GetSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[sample_query_service.GetSampleQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_get_sample_query( + self, response: sample_query.SampleQuery + ) -> sample_query.SampleQuery: + """Post-rpc interceptor for get_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_import_sample_queries( + self, + request: import_config.ImportSampleQueriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[import_config.ImportSampleQueriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_sample_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_import_sample_queries( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_sample_queries + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_list_sample_queries( + self, + request: sample_query_service.ListSampleQueriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.ListSampleQueriesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_sample_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_list_sample_queries( + self, response: sample_query_service.ListSampleQueriesResponse + ) -> sample_query_service.ListSampleQueriesResponse: + """Post-rpc interceptor for list_sample_queries + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_update_sample_query( + self, + request: sample_query_service.UpdateSampleQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_service.UpdateSampleQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_sample_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_update_sample_query( + self, response: gcd_sample_query.SampleQuery + ) -> gcd_sample_query.SampleQuery: + """Post-rpc interceptor for update_sample_query + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQueryService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SampleQueryService 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 SampleQueryService 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 SampleQueryService 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 SampleQueryService 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 SampleQueryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SampleQueryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SampleQueryServiceRestInterceptor + + +class SampleQueryServiceRestTransport(SampleQueryServiceTransport): + """REST backend transport for SampleQueryService. + + Service for managing + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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[SampleQueryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 SampleQueryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "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 _CreateSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("CreateSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sampleQueryId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.CreateSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Call the create sample query method over HTTP. + + Args: + request (~.sample_query_service.CreateSampleQueryRequest): + The request object. Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/sampleQuerySets/*}/sampleQueries", + "body": "sample_query", + }, + ] + request, metadata = self._interceptor.pre_create_sample_query( + request, metadata + ) + pb_request = sample_query_service.CreateSampleQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query.SampleQuery() + pb_resp = gcd_sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sample_query(resp) + return resp + + class _DeleteSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("DeleteSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.DeleteSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete sample query method over HTTP. + + Args: + request (~.sample_query_service.DeleteSampleQueryRequest): + The request object. Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/sampleQuerySets/*/sampleQueries/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_sample_query( + request, metadata + ) + pb_request = sample_query_service.DeleteSampleQueryRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 _GetSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("GetSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.GetSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query.SampleQuery: + r"""Call the get sample query method over HTTP. + + Args: + request (~.sample_query_service.GetSampleQueryRequest): + The request object. Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}", + }, + ] + request, metadata = self._interceptor.pre_get_sample_query( + request, metadata + ) + pb_request = sample_query_service.GetSampleQueryRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query.SampleQuery() + pb_resp = sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_sample_query(resp) + return resp + + class _ImportSampleQueries(SampleQueryServiceRestStub): + def __hash__(self): + return hash("ImportSampleQueries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_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.ImportSampleQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the import sample queries method over HTTP. + + Args: + request (~.import_config.ImportSampleQueriesRequest): + The request object. Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The 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/*/sampleQuerySets/*}/sampleQueries:import", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_import_sample_queries( + request, metadata + ) + pb_request = import_config.ImportSampleQueriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_queries(resp) + return resp + + class _ListSampleQueries(SampleQueryServiceRestStub): + def __hash__(self): + return hash("ListSampleQueries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.ListSampleQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_service.ListSampleQueriesResponse: + r"""Call the list sample queries method over HTTP. + + Args: + request (~.sample_query_service.ListSampleQueriesRequest): + The request object. Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_service.ListSampleQueriesResponse: + Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/sampleQuerySets/*}/sampleQueries", + }, + ] + request, metadata = self._interceptor.pre_list_sample_queries( + request, metadata + ) + pb_request = sample_query_service.ListSampleQueriesRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_service.ListSampleQueriesResponse() + pb_resp = sample_query_service.ListSampleQueriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sample_queries(resp) + return resp + + class _UpdateSampleQuery(SampleQueryServiceRestStub): + def __hash__(self): + return hash("UpdateSampleQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_service.UpdateSampleQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query.SampleQuery: + r"""Call the update sample query method over HTTP. + + Args: + request (~.sample_query_service.UpdateSampleQueryRequest): + The request object. Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query.SampleQuery: + Sample Query captures metadata to be + used for evaluation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{sample_query.name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}", + "body": "sample_query", + }, + ] + request, metadata = self._interceptor.pre_update_sample_query( + request, metadata + ) + pb_request = sample_query_service.UpdateSampleQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query.SampleQuery() + pb_resp = gcd_sample_query.SampleQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_sample_query(resp) + return resp + + @property + def create_sample_query( + self, + ) -> Callable[ + [sample_query_service.CreateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sample_query( + self, + ) -> Callable[[sample_query_service.DeleteSampleQueryRequest], 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._DeleteSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sample_query( + self, + ) -> Callable[ + [sample_query_service.GetSampleQueryRequest], sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_sample_queries( + self, + ) -> Callable[[import_config.ImportSampleQueriesRequest], 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._ImportSampleQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sample_queries( + self, + ) -> Callable[ + [sample_query_service.ListSampleQueriesRequest], + sample_query_service.ListSampleQueriesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSampleQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sample_query( + self, + ) -> Callable[ + [sample_query_service.UpdateSampleQueryRequest], gcd_sample_query.SampleQuery + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSampleQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SampleQueryServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SampleQueryServiceRestStub): + 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/*/dataConnector/operations/*}", + }, + { + "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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/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(SampleQueryServiceRestStub): + 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/*/dataConnector}/operations", + }, + { + "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__ = ("SampleQueryServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/__init__.py new file mode 100644 index 000000000000..59b993474e98 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SampleQuerySetServiceAsyncClient +from .client import SampleQuerySetServiceClient + +__all__ = ( + "SampleQuerySetServiceClient", + "SampleQuerySetServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/async_client.py new file mode 100644 index 000000000000..583718ce0f53 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/async_client.py @@ -0,0 +1,1130 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.services.sample_query_set_service import pagers +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +from .client import SampleQuerySetServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .transports.grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport + + +class SampleQuerySetServiceAsyncClient: + """Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s, + """ + + _client: SampleQuerySetServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SampleQuerySetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + + location_path = staticmethod(SampleQuerySetServiceClient.location_path) + parse_location_path = staticmethod(SampleQuerySetServiceClient.parse_location_path) + sample_query_set_path = staticmethod( + SampleQuerySetServiceClient.sample_query_set_path + ) + parse_sample_query_set_path = staticmethod( + SampleQuerySetServiceClient.parse_sample_query_set_path + ) + common_billing_account_path = staticmethod( + SampleQuerySetServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SampleQuerySetServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SampleQuerySetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SampleQuerySetServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SampleQuerySetServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SampleQuerySetServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SampleQuerySetServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SampleQuerySetServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SampleQuerySetServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SampleQuerySetServiceClient.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: + SampleQuerySetServiceAsyncClient: The constructed client. + """ + return SampleQuerySetServiceClient.from_service_account_info.__func__(SampleQuerySetServiceAsyncClient, 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: + SampleQuerySetServiceAsyncClient: The constructed client. + """ + return SampleQuerySetServiceClient.from_service_account_file.__func__(SampleQuerySetServiceAsyncClient, 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 SampleQuerySetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SampleQuerySetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQuerySetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(SampleQuerySetServiceClient).get_transport_class, + type(SampleQuerySetServiceClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQuerySetServiceTransport, + Callable[..., SampleQuerySetServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query set service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQuerySetServiceTransport,Callable[..., SampleQuerySetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQuerySetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SampleQuerySetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.GetSampleQuerySetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.GetSampleQuerySetRequest): + request = sample_query_set_service.GetSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sample_query_sets( + self, + request: Optional[ + Union[sample_query_set_service.ListSampleQuerySetsRequest, 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.ListSampleQuerySetsAsyncPager: + r"""Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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_sample_query_sets(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + parent (:class:`str`): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + under this location, regardless of whether or not this + location 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.ListSampleQuerySetsRequest): + request = sample_query_set_service.ListSampleQuerySetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sample_query_sets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSampleQuerySetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.CreateSampleQuerySetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = None, + sample_query_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = await client.create_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set (:class:`google.cloud.discoveryengine_v1beta.types.SampleQuerySet`): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to create. + + This corresponds to the ``sample_query_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set_id (:class:`str`): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1beta.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQuerySetRequest.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 ``sample_query_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query_set, sample_query_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.CreateSampleQuerySetRequest + ): + request = sample_query_set_service.CreateSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if sample_query_set_id is not None: + request.sample_query_set_id = sample_query_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.UpdateSampleQuerySetRequest, dict] + ] = None, + *, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = 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_sample_query_set.SampleQuerySet: + r"""Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = await client.update_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet] + method. + sample_query_set (:class:`google.cloud.discoveryengine_v1beta.types.SampleQuerySet`): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query_set`` 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 imported 'sample query set' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.UpdateSampleQuerySetRequest + ): + request = sample_query_set_service.UpdateSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query_set.name", request.sample_query_set.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.DeleteSampleQuerySetRequest, dict] + ] = 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 + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query_set(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest, dict]]): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet] + method. + name (:class:`str`): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.DeleteSampleQuerySetRequest + ): + request = sample_query_set_service.DeleteSampleQuerySetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sample_query_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SampleQuerySetServiceAsyncClient": + 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__ = ("SampleQuerySetServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/client.py new file mode 100644 index 000000000000..83f5598ee7a7 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/client.py @@ -0,0 +1,1553 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.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 google.cloud.discoveryengine_v1beta.services.sample_query_set_service import pagers +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +from .transports.base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .transports.grpc import SampleQuerySetServiceGrpcTransport +from .transports.grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport +from .transports.rest import SampleQuerySetServiceRestTransport + + +class SampleQuerySetServiceClientMeta(type): + """Metaclass for the SampleQuerySetService 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[SampleQuerySetServiceTransport]] + _transport_registry["grpc"] = SampleQuerySetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SampleQuerySetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SampleQuerySetServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SampleQuerySetServiceTransport]: + """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 SampleQuerySetServiceClient(metaclass=SampleQuerySetServiceClientMeta): + """Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SampleQuerySetServiceClient: 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: + SampleQuerySetServiceClient: 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) -> SampleQuerySetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SampleQuerySetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def 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_location_path(path: str) -> Dict[str, str]: + """Parses a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def sample_query_set_path( + project: str, + location: str, + sample_query_set: str, + ) -> str: + """Returns a fully-qualified sample_query_set string.""" + return "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + + @staticmethod + def parse_sample_query_set_path(path: str) -> Dict[str, str]: + """Parses a sample_query_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sampleQuerySets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or SampleQuerySetServiceClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SampleQuerySetServiceTransport, + Callable[..., SampleQuerySetServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sample query set service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SampleQuerySetServiceTransport,Callable[..., SampleQuerySetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SampleQuerySetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SampleQuerySetServiceClient._read_environment_variables() + self._client_cert_source = SampleQuerySetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SampleQuerySetServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SampleQuerySetServiceTransport) + if transport_provided: + # transport is a SampleQuerySetServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SampleQuerySetServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SampleQuerySetServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SampleQuerySetServiceTransport], + Callable[..., SampleQuerySetServiceTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SampleQuerySetServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.GetSampleQuerySetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet] + method. + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.GetSampleQuerySetRequest): + request = sample_query_set_service.GetSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sample_query_sets( + self, + request: Optional[ + Union[sample_query_set_service.ListSampleQuerySetsRequest, 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.ListSampleQuerySetsPager: + r"""Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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_sample_query_sets(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest, dict]): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + under this location, regardless of whether or not this + location 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.sample_query_set_service.pagers.ListSampleQuerySetsPager: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sample_query_set_service.ListSampleQuerySetsRequest): + request = sample_query_set_service.ListSampleQuerySetsRequest(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_sample_query_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSampleQuerySetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.CreateSampleQuerySetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = None, + sample_query_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = client.create_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to create. + + This corresponds to the ``sample_query_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sample_query_set_id (str): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1beta.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQuerySetRequest.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 ``sample_query_set_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.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, sample_query_set, sample_query_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.CreateSampleQuerySetRequest + ): + request = sample_query_set_service.CreateSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sample_query_set is not None: + request.sample_query_set = sample_query_set + if sample_query_set_id is not None: + request.sample_query_set_id = sample_query_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.UpdateSampleQuerySetRequest, dict] + ] = None, + *, + sample_query_set: Optional[gcd_sample_query_set.SampleQuerySet] = 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_sample_query_set.SampleQuerySet: + r"""Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = client.update_sample_query_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet] + method. + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to update does not exist a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``sample_query_set`` 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 imported 'sample query set' to + update. If not set, will by default + update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([sample_query_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.UpdateSampleQuerySetRequest + ): + request = sample_query_set_service.UpdateSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sample_query_set is not None: + request.sample_query_set = sample_query_set + 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sample_query_set.name", request.sample_query_set.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sample_query_set( + self, + request: Optional[ + Union[sample_query_set_service.DeleteSampleQuerySetRequest, dict] + ] = 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 + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query_set(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest, dict]): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet] + method. + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, sample_query_set_service.DeleteSampleQuerySetRequest + ): + request = sample_query_set_service.DeleteSampleQuerySetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sample_query_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "SampleQuerySetServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SampleQuerySetServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/pagers.py new file mode 100644 index 000000000000..8f288adea94d --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set, + sample_query_set_service, +) + + +class ListSampleQuerySetsPager: + """A pager for iterating through ``list_sample_query_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sample_query_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSampleQuerySets`` requests and continue to iterate + through the ``sample_query_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse` + 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[..., sample_query_set_service.ListSampleQuerySetsResponse], + request: sample_query_set_service.ListSampleQuerySetsRequest, + response: sample_query_set_service.ListSampleQuerySetsResponse, + *, + 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.ListSampleQuerySetsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse): + 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 = sample_query_set_service.ListSampleQuerySetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[sample_query_set_service.ListSampleQuerySetsResponse]: + 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[sample_query_set.SampleQuerySet]: + for page in self.pages: + yield from page.sample_query_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSampleQuerySetsAsyncPager: + """A pager for iterating through ``list_sample_query_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sample_query_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSampleQuerySets`` requests and continue to iterate + through the ``sample_query_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse` + 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[sample_query_set_service.ListSampleQuerySetsResponse] + ], + request: sample_query_set_service.ListSampleQuerySetsRequest, + response: sample_query_set_service.ListSampleQuerySetsResponse, + *, + 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.ListSampleQuerySetsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsResponse): + 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 = sample_query_set_service.ListSampleQuerySetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[sample_query_set_service.ListSampleQuerySetsResponse]: + 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[sample_query_set.SampleQuerySet]: + async def async_generator(): + async for page in self.pages: + for response in page.sample_query_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/__init__.py new file mode 100644 index 000000000000..63205c014885 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 SampleQuerySetServiceTransport +from .grpc import SampleQuerySetServiceGrpcTransport +from .grpc_asyncio import SampleQuerySetServiceGrpcAsyncIOTransport +from .rest import ( + SampleQuerySetServiceRestInterceptor, + SampleQuerySetServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SampleQuerySetServiceTransport]] +_transport_registry["grpc"] = SampleQuerySetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SampleQuerySetServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SampleQuerySetServiceRestTransport + +__all__ = ( + "SampleQuerySetServiceTransport", + "SampleQuerySetServiceGrpcTransport", + "SampleQuerySetServiceGrpcAsyncIOTransport", + "SampleQuerySetServiceRestTransport", + "SampleQuerySetServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/base.py new file mode 100644 index 000000000000..875021863bec --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/base.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SampleQuerySetServiceTransport(abc.ABC): + """Abstract transport class for SampleQuerySetService.""" + + 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 (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_sample_query_set: gapic_v1.method.wrap_method( + self.get_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_query_sets: gapic_v1.method.wrap_method( + self.list_sample_query_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query_set: gapic_v1.method.wrap_method( + self.create_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query_set: gapic_v1.method.wrap_method( + self.update_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query_set: gapic_v1.method.wrap_method( + self.delete_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + Union[ + sample_query_set.SampleQuerySet, Awaitable[sample_query_set.SampleQuerySet] + ], + ]: + raise NotImplementedError() + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + Union[ + sample_query_set_service.ListSampleQuerySetsResponse, + Awaitable[sample_query_set_service.ListSampleQuerySetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + Union[ + gcd_sample_query_set.SampleQuerySet, + Awaitable[gcd_sample_query_set.SampleQuerySet], + ], + ]: + raise NotImplementedError() + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + Union[ + gcd_sample_query_set.SampleQuerySet, + Awaitable[gcd_sample_query_set.SampleQuerySet], + ], + ]: + raise NotImplementedError() + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SampleQuerySetServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc.py new file mode 100644 index 000000000000..c0961c4dd9aa --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +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 +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport + + +class SampleQuerySetServiceGrpcTransport(SampleQuerySetServiceTransport): + """gRPC backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "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 get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the get sample query set method over gRPC. + + Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.GetSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query_set" not in self._stubs: + self._stubs["get_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/GetSampleQuerySet", + request_serializer=sample_query_set_service.GetSampleQuerySetRequest.serialize, + response_deserializer=sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["get_sample_query_set"] + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + sample_query_set_service.ListSampleQuerySetsResponse, + ]: + r"""Return a callable for the list sample query sets method over gRPC. + + Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s. + + Returns: + Callable[[~.ListSampleQuerySetsRequest], + ~.ListSampleQuerySetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_sets" not in self._stubs: + self._stubs["list_sample_query_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/ListSampleQuerySets", + request_serializer=sample_query_set_service.ListSampleQuerySetsRequest.serialize, + response_deserializer=sample_query_set_service.ListSampleQuerySetsResponse.deserialize, + ) + return self._stubs["list_sample_query_sets"] + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the create sample query set method over gRPC. + + Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + + Returns: + Callable[[~.CreateSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["create_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/CreateSampleQuerySet", + request_serializer=sample_query_set_service.CreateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["create_sample_query_set"] + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + r"""Return a callable for the update sample query set method over gRPC. + + Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.UpdateSampleQuerySetRequest], + ~.SampleQuerySet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["update_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/UpdateSampleQuerySet", + request_serializer=sample_query_set_service.UpdateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["update_sample_query_set"] + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete sample query set method over gRPC. + + Deletes a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.DeleteSampleQuerySetRequest], + ~.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_sample_query_set" not in self._stubs: + self._stubs["delete_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/DeleteSampleQuerySet", + request_serializer=sample_query_set_service.DeleteSampleQuerySetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query_set"] + + def close(self): + self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SampleQuerySetServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..44aa5b56af25 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/grpc_asyncio.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO, SampleQuerySetServiceTransport +from .grpc import SampleQuerySetServiceGrpcTransport + + +class SampleQuerySetServiceGrpcAsyncIOTransport(SampleQuerySetServiceTransport): + """gRPC AsyncIO backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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`. + 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[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + Awaitable[sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the get sample query set method over gRPC. + + Gets a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.GetSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_sample_query_set" not in self._stubs: + self._stubs["get_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/GetSampleQuerySet", + request_serializer=sample_query_set_service.GetSampleQuerySetRequest.serialize, + response_deserializer=sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["get_sample_query_set"] + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + Awaitable[sample_query_set_service.ListSampleQuerySetsResponse], + ]: + r"""Return a callable for the list sample query sets method over gRPC. + + Gets a list of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s. + + Returns: + Callable[[~.ListSampleQuerySetsRequest], + Awaitable[~.ListSampleQuerySetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_sets" not in self._stubs: + self._stubs["list_sample_query_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/ListSampleQuerySets", + request_serializer=sample_query_set_service.ListSampleQuerySetsRequest.serialize, + response_deserializer=sample_query_set_service.ListSampleQuerySetsResponse.deserialize, + ) + return self._stubs["list_sample_query_sets"] + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + Awaitable[gcd_sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the create sample query set method over gRPC. + + Creates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + + Returns: + Callable[[~.CreateSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["create_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/CreateSampleQuerySet", + request_serializer=sample_query_set_service.CreateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["create_sample_query_set"] + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + Awaitable[gcd_sample_query_set.SampleQuerySet], + ]: + r"""Return a callable for the update sample query set method over gRPC. + + Updates a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.UpdateSampleQuerySetRequest], + Awaitable[~.SampleQuerySet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sample_query_set" not in self._stubs: + self._stubs["update_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/UpdateSampleQuerySet", + request_serializer=sample_query_set_service.UpdateSampleQuerySetRequest.serialize, + response_deserializer=gcd_sample_query_set.SampleQuerySet.deserialize, + ) + return self._stubs["update_sample_query_set"] + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete sample query set method over gRPC. + + Deletes a + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Returns: + Callable[[~.DeleteSampleQuerySetRequest], + 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_sample_query_set" not in self._stubs: + self._stubs["delete_sample_query_set"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SampleQuerySetService/DeleteSampleQuerySet", + request_serializer=sample_query_set_service.DeleteSampleQuerySetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sample_query_set"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_sample_query_set: gapic_v1.method_async.wrap_method( + self.get_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.list_sample_query_sets: gapic_v1.method_async.wrap_method( + self.list_sample_query_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_sample_query_set: gapic_v1.method_async.wrap_method( + self.create_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.update_sample_query_set: gapic_v1.method_async.wrap_method( + self.update_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_sample_query_set: gapic_v1.method_async.wrap_method( + self.delete_sample_query_set, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SampleQuerySetServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py new file mode 100644 index 000000000000..11b29a70f968 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py @@ -0,0 +1,1241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_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.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 +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SampleQuerySetServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SampleQuerySetServiceRestInterceptor: + """Interceptor for SampleQuerySetService. + + 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 SampleQuerySetServiceRestTransport. + + .. code-block:: python + class MyCustomSampleQuerySetServiceInterceptor(SampleQuerySetServiceRestInterceptor): + def pre_create_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sample_query_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sample_query_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sample_query_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sample_query_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SampleQuerySetServiceRestTransport(interceptor=MyCustomSampleQuerySetServiceInterceptor()) + client = SampleQuerySetServiceClient(transport=transport) + + + """ + + def pre_create_sample_query_set( + self, + request: sample_query_set_service.CreateSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.CreateSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_create_sample_query_set( + self, response: gcd_sample_query_set.SampleQuerySet + ) -> gcd_sample_query_set.SampleQuerySet: + """Post-rpc interceptor for create_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_delete_sample_query_set( + self, + request: sample_query_set_service.DeleteSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.DeleteSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def pre_get_sample_query_set( + self, + request: sample_query_set_service.GetSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.GetSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_get_sample_query_set( + self, response: sample_query_set.SampleQuerySet + ) -> sample_query_set.SampleQuerySet: + """Post-rpc interceptor for get_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_list_sample_query_sets( + self, + request: sample_query_set_service.ListSampleQuerySetsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.ListSampleQuerySetsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_sample_query_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_list_sample_query_sets( + self, response: sample_query_set_service.ListSampleQuerySetsResponse + ) -> sample_query_set_service.ListSampleQuerySetsResponse: + """Post-rpc interceptor for list_sample_query_sets + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_update_sample_query_set( + self, + request: sample_query_set_service.UpdateSampleQuerySetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + sample_query_set_service.UpdateSampleQuerySetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_sample_query_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_update_sample_query_set( + self, response: gcd_sample_query_set.SampleQuerySet + ) -> gcd_sample_query_set.SampleQuerySet: + """Post-rpc interceptor for update_sample_query_set + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SampleQuerySetService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService 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 SampleQuerySetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SampleQuerySetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SampleQuerySetServiceRestInterceptor + + +class SampleQuerySetServiceRestTransport(SampleQuerySetServiceTransport): + """REST backend transport for SampleQuerySetService. + + Service for managing + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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[SampleQuerySetServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 SampleQuerySetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("CreateSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sampleQuerySetId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.CreateSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Call the create sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.CreateSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/sampleQuerySets", + "body": "sample_query_set", + }, + ] + request, metadata = self._interceptor.pre_create_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.CreateSampleQuerySetRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query_set.SampleQuerySet() + pb_resp = gcd_sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sample_query_set(resp) + return resp + + class _DeleteSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("DeleteSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.DeleteSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.DeleteSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/sampleQuerySets/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.DeleteSampleQuerySetRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 _GetSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("GetSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.GetSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set.SampleQuerySet: + r"""Call the get sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.GetSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.GetSampleQuerySetRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_set.SampleQuerySet() + pb_resp = sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_sample_query_set(resp) + return resp + + class _ListSampleQuerySets(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("ListSampleQuerySets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.ListSampleQuerySetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> sample_query_set_service.ListSampleQuerySetsResponse: + r"""Call the list sample query sets method over HTTP. + + Args: + request (~.sample_query_set_service.ListSampleQuerySetsRequest): + The request object. Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.sample_query_set_service.ListSampleQuerySetsResponse: + Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/sampleQuerySets", + }, + ] + request, metadata = self._interceptor.pre_list_sample_query_sets( + request, metadata + ) + pb_request = sample_query_set_service.ListSampleQuerySetsRequest.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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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 = sample_query_set_service.ListSampleQuerySetsResponse() + pb_resp = sample_query_set_service.ListSampleQuerySetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sample_query_sets(resp) + return resp + + class _UpdateSampleQuerySet(SampleQuerySetServiceRestStub): + def __hash__(self): + return hash("UpdateSampleQuerySet") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: sample_query_set_service.UpdateSampleQuerySetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_sample_query_set.SampleQuerySet: + r"""Call the update sample query set method over HTTP. + + Args: + request (~.sample_query_set_service.UpdateSampleQuerySetRequest): + The request object. Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_sample_query_set.SampleQuerySet: + A SampleQuerySet is the parent + resource of SampleQuery, and contains + the configurations shared by all + SampleQuery under it. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{sample_query_set.name=projects/*/locations/*/sampleQuerySets/*}", + "body": "sample_query_set", + }, + ] + request, metadata = self._interceptor.pre_update_sample_query_set( + request, metadata + ) + pb_request = sample_query_set_service.UpdateSampleQuerySetRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._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_sample_query_set.SampleQuerySet() + pb_resp = gcd_sample_query_set.SampleQuerySet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_sample_query_set(resp) + return resp + + @property + def create_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.CreateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.DeleteSampleQuerySetRequest], 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._DeleteSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.GetSampleQuerySetRequest], + sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sample_query_sets( + self, + ) -> Callable[ + [sample_query_set_service.ListSampleQuerySetsRequest], + sample_query_set_service.ListSampleQuerySetsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSampleQuerySets(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sample_query_set( + self, + ) -> Callable[ + [sample_query_set_service.UpdateSampleQuerySetRequest], + gcd_sample_query_set.SampleQuerySet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSampleQuerySet(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SampleQuerySetServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SampleQuerySetServiceRestStub): + 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/*/dataConnector/operations/*}", + }, + { + "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/*/evaluations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/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(SampleQuerySetServiceRestStub): + 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/*/dataConnector}/operations", + }, + { + "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__ = ("SampleQuerySetServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py index a3a9ba6206e6..f919f6bcac33 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py @@ -468,10 +468,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -1221,10 +1229,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py index 40734c90ff47..b4d1f3bf66e5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py @@ -68,6 +68,8 @@ class SearchServiceAsyncClient: branch_path = staticmethod(SearchServiceClient.branch_path) parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + chunk_path = staticmethod(SearchServiceClient.chunk_path) + parse_chunk_path = staticmethod(SearchServiceClient.parse_chunk_path) data_store_path = staticmethod(SearchServiceClient.data_store_path) parse_data_store_path = staticmethod(SearchServiceClient.parse_data_store_path) document_path = staticmethod(SearchServiceClient.document_path) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py index c42f322fd40f..1460e47f959a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py @@ -208,6 +208,34 @@ def parse_branch_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def chunk_path( + project: str, + location: str, + data_store: str, + branch: str, + document: str, + chunk: str, + ) -> str: + """Returns a fully-qualified chunk string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}/chunks/{chunk}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + chunk=chunk, + ) + + @staticmethod + def parse_chunk_path(path: str) -> Dict[str, str]: + """Parses a chunk path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)/chunks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_store_path( project: str, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py index 13ea840eec3f..75751c19c4f1 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py @@ -527,10 +527,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py index 8ebb6417b614..f00eee6f962f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py @@ -380,10 +380,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -822,10 +830,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py index 4e4095433f92..64ab0ef59339 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py @@ -829,10 +829,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py index 8b8eb9e76fea..974a3ea5e24f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py @@ -718,10 +718,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -2277,10 +2285,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py index 1802f3f2cc2b..2e4dce4f8bce 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py @@ -413,10 +413,18 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", @@ -1022,10 +1030,18 @@ def __call__( "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/evaluations/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sampleQuerySets/*/operations/*}", + }, { "method": "get", "uri": "/v1beta/{name=projects/*/operations/*}", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py index c79184d5e0b9..533f54458f0b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py @@ -14,6 +14,7 @@ # limitations under the License. # from .answer import Answer +from .chunk import Chunk from .common import ( CustomAttribute, DoubleList, @@ -101,6 +102,16 @@ TuneEngineResponse, UpdateEngineRequest, ) +from .evaluation import Evaluation, QualityMetrics +from .evaluation_service import ( + CreateEvaluationMetadata, + CreateEvaluationRequest, + GetEvaluationRequest, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, +) from .grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, @@ -119,6 +130,9 @@ ImportDocumentsRequest, ImportDocumentsResponse, ImportErrorConfig, + ImportSampleQueriesMetadata, + ImportSampleQueriesRequest, + ImportSampleQueriesResponse, ImportSuggestionDenyListEntriesMetadata, ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, @@ -139,6 +153,24 @@ ) from .rank_service import RankingRecord, RankRequest, RankResponse from .recommendation_service import RecommendRequest, RecommendResponse +from .sample_query import SampleQuery +from .sample_query_service import ( + CreateSampleQueryRequest, + DeleteSampleQueryRequest, + GetSampleQueryRequest, + ListSampleQueriesRequest, + ListSampleQueriesResponse, + UpdateSampleQueryRequest, +) +from .sample_query_set import SampleQuerySet +from .sample_query_set_service import ( + CreateSampleQuerySetRequest, + DeleteSampleQuerySetRequest, + GetSampleQuerySetRequest, + ListSampleQuerySetsRequest, + ListSampleQuerySetsResponse, + UpdateSampleQuerySetRequest, +) from .schema import Schema from .schema_service import ( CreateSchemaMetadata, @@ -211,6 +243,7 @@ __all__ = ( "Answer", + "Chunk", "CustomAttribute", "DoubleList", "EmbeddingConfig", @@ -286,6 +319,15 @@ "TuneEngineRequest", "TuneEngineResponse", "UpdateEngineRequest", + "Evaluation", + "QualityMetrics", + "CreateEvaluationMetadata", + "CreateEvaluationRequest", + "GetEvaluationRequest", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", @@ -302,6 +344,9 @@ "ImportDocumentsRequest", "ImportDocumentsResponse", "ImportErrorConfig", + "ImportSampleQueriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", "ImportSuggestionDenyListEntriesMetadata", "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", @@ -323,6 +368,20 @@ "RankResponse", "RecommendRequest", "RecommendResponse", + "SampleQuery", + "CreateSampleQueryRequest", + "DeleteSampleQueryRequest", + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "UpdateSampleQueryRequest", + "SampleQuerySet", + "CreateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "UpdateSampleQuerySetRequest", "Schema", "CreateSchemaMetadata", "CreateSchemaRequest", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/chunk.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/chunk.py new file mode 100644 index 000000000000..0a096b6a53c1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/chunk.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Chunk", + }, +) + + +class Chunk(proto.Message): + r"""Chunk captures all raw metadata information of items to be + recommended or searched in the chunk mode. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The full resource name of the chunk. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}/chunks/{chunk_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Unique chunk ID of the current chunk. + content (str): + Content is a string from a document (parsed + content). + relevance_score (float): + Output only. Represents the relevance score based on + similarity. Higher score indicates higher chunk relevance. + The score is in range [-1.0, 1.0]. Only populated on + [SearchService.SearchResponse][]. + + This field is a member of `oneof`_ ``_relevance_score``. + document_metadata (google.cloud.discoveryengine_v1beta.types.Chunk.DocumentMetadata): + Metadata of the document from the current + chunk. + 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. + page_span (google.cloud.discoveryengine_v1beta.types.Chunk.PageSpan): + Page span of the chunk. + chunk_metadata (google.cloud.discoveryengine_v1beta.types.Chunk.ChunkMetadata): + Output only. Metadata of the current chunk. + """ + + class DocumentMetadata(proto.Message): + r"""Document metadata contains the information of the document of + the current chunk. + + Attributes: + uri (str): + Uri of the document. + title (str): + Title of the document. + struct_data (google.protobuf.struct_pb2.Struct): + Data representation. 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. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + class PageSpan(proto.Message): + r"""Page span of the chunk. + + Attributes: + page_start (int): + The start page of the chunk. + page_end (int): + The end page of the chunk. + """ + + page_start: int = proto.Field( + proto.INT32, + number=1, + ) + page_end: int = proto.Field( + proto.INT32, + number=2, + ) + + class ChunkMetadata(proto.Message): + r"""Metadata of the current chunk. This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + + Attributes: + previous_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.Chunk]): + The previous chunks of the current chunk. The number is + controlled by + [SearchRequest.ContentSearchSpec.ChunkSpec.num_previous_chunks][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.ChunkSpec.num_previous_chunks]. + This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + next_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.Chunk]): + The next chunks of the current chunk. The number is + controlled by + [SearchRequest.ContentSearchSpec.ChunkSpec.num_next_chunks][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.ChunkSpec.num_next_chunks]. + This field is only populated on + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API. + """ + + previous_chunks: MutableSequence["Chunk"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Chunk", + ) + next_chunks: MutableSequence["Chunk"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Chunk", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + content: str = proto.Field( + proto.STRING, + number=3, + ) + relevance_score: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + document_metadata: DocumentMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=DocumentMetadata, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + page_span: PageSpan = proto.Field( + proto.MESSAGE, + number=6, + message=PageSpan, + ) + chunk_metadata: ChunkMetadata = proto.Field( + proto.MESSAGE, + number=7, + message=ChunkMetadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py index 43f8e3e5c3ea..debc0078337a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py @@ -636,6 +636,10 @@ class SearchParams(proto.Message): If this field is unrecognizable, an ``INVALID_ARGUMENT`` is returned. + search_result_mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SearchResultMode): + Specifies the search result mode. If unspecified, the search + result mode defaults to ``DOCUMENTS``. See `parse and chunk + documents `__ data_store_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.DataStoreSpec]): Specs defining dataStores to filter on in a search call and configurations for those @@ -662,6 +666,11 @@ class SearchParams(proto.Message): proto.STRING, number=4, ) + search_result_mode: search_service.SearchRequest.ContentSearchSpec.SearchResultMode = proto.Field( + proto.ENUM, + number=5, + enum=search_service.SearchRequest.ContentSearchSpec.SearchResultMode, + ) data_store_specs: MutableSequence[ search_service.SearchRequest.DataStoreSpec ] = proto.RepeatedField( @@ -995,8 +1004,8 @@ class AnswerQueryResponse(proto.Message): Attributes: answer (google.cloud.discoveryengine_v1beta.types.Answer): Answer resource object. If - [AnswerQueryRequest.StepSpec.max_step_count][] is greater - than 1, use + [AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps][google.cloud.discoveryengine.v1beta.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps] + is greater than 1, use [Answer.name][google.cloud.discoveryengine.v1beta.Answer.name] to fetch answer information using [ConversationalSearchService.GetAnswer][google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetAnswer] diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document.py index 1391df967661..00619f5b456e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document.py @@ -119,7 +119,7 @@ class Content(proto.Message): 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 2.5 MB for text-based formats, 100 MB + maximum file size is 2.5 MB for text-based formats, 200 MB for other formats. This field is a member of `oneof`_ ``content``. diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py index 265d0661748d..ee06ee0d8a47 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py @@ -41,6 +41,8 @@ class DocumentProcessingConfig(proto.Message): The full resource name of the Document Processing Config. Format: ``projects/*/locations/*/collections/*/dataStores/*/documentProcessingConfig``. + chunking_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ChunkingConfig): + Whether chunking mode is enabled. default_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig): Configurations for default Document parser. If not specified, we will configure it as @@ -55,11 +57,58 @@ class DocumentProcessingConfig(proto.Message): digital parsing, ocr parsing or layout parsing is supported. - ``html``: Override parsing config for HTML files, only - digital parsing and or layout parsing are supported. + digital parsing and layout parsing are supported. - ``docx``: Override parsing config for DOCX files, only - digital parsing and or layout parsing are supported. + digital parsing and layout parsing are supported. + - ``pptx``: Override parsing config for PPTX files, only + digital parsing and layout parsing are supported. """ + class ChunkingConfig(proto.Message): + r"""Configuration for chunking config. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + layout_based_chunking_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig): + Configuration for the layout based chunking. + + This field is a member of `oneof`_ ``chunk_mode``. + """ + + class LayoutBasedChunkingConfig(proto.Message): + r"""Configuration for the layout based chunking. + + Attributes: + chunk_size (int): + The token size limit for each chunk. + + Supported values: 100-500 (inclusive). + Default value: 500. + include_ancestor_headings (bool): + Whether to include appending different levels + of headings to chunks from the middle of the + document to prevent context loss. + + Default value: False. + """ + + chunk_size: int = proto.Field( + proto.INT32, + number=1, + ) + include_ancestor_headings: bool = proto.Field( + proto.BOOL, + number=2, + ) + + layout_based_chunking_config: "DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="chunk_mode", + message="DocumentProcessingConfig.ChunkingConfig.LayoutBasedChunkingConfig", + ) + class ParsingConfig(proto.Message): r"""Related configurations applied to a specific type of document parser. @@ -80,6 +129,10 @@ class ParsingConfig(proto.Message): Configurations applied to OCR parser. Currently it only applies to PDFs. + This field is a member of `oneof`_ ``type_dedicated_config``. + layout_parsing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig): + Configurations applied to layout parser. + This field is a member of `oneof`_ ``type_dedicated_config``. """ @@ -108,6 +161,9 @@ class OcrParsingConfig(proto.Message): number=2, ) + class LayoutParsingConfig(proto.Message): + r"""The layout parsing configurations for documents.""" + digital_parsing_config: "DocumentProcessingConfig.ParsingConfig.DigitalParsingConfig" = proto.Field( proto.MESSAGE, number=1, @@ -120,11 +176,22 @@ class OcrParsingConfig(proto.Message): oneof="type_dedicated_config", message="DocumentProcessingConfig.ParsingConfig.OcrParsingConfig", ) + layout_parsing_config: "DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig" = proto.Field( + proto.MESSAGE, + number=3, + oneof="type_dedicated_config", + message="DocumentProcessingConfig.ParsingConfig.LayoutParsingConfig", + ) name: str = proto.Field( proto.STRING, number=1, ) + chunking_config: ChunkingConfig = proto.Field( + proto.MESSAGE, + number=3, + message=ChunkingConfig, + ) default_parsing_config: ParsingConfig = proto.Field( proto.MESSAGE, number=4, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation.py new file mode 100644 index 000000000000..86b9c01d8251 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "Evaluation", + "QualityMetrics", + }, +) + + +class Evaluation(proto.Message): + r"""An evaluation is a single execution (or run) of an evaluation + process. It encapsulates the state of the evaluation and the + resulting data. + + Attributes: + name (str): + Identifier. The full resource name of the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + in the format of + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + evaluation_spec (google.cloud.discoveryengine_v1beta.types.Evaluation.EvaluationSpec): + Required. The specification of the + evaluation. + quality_metrics (google.cloud.discoveryengine_v1beta.types.QualityMetrics): + Output only. The metrics produced by the evaluation, + averaged across all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + in the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + + Only populated when the evaluation's state is SUCCEEDED. + state (google.cloud.discoveryengine_v1beta.types.Evaluation.State): + Output only. The state of the evaluation. + error (google.rpc.status_pb2.Status): + Output only. The error that occurred during + evaluation. Only populated when the evaluation's + state is FAILED. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + was created at. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + was completed at. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + Output only. A sample of errors encountered + while processing the request. + """ + + class State(proto.Enum): + r"""Describes the state of an evaluation. + + Values: + STATE_UNSPECIFIED (0): + The evaluation is unspecified. + PENDING (1): + The service is preparing to run the + evaluation. + RUNNING (2): + The evaluation is in progress. + SUCCEEDED (3): + The evaluation completed successfully. + FAILED (4): + The evaluation failed. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + FAILED = 4 + + class EvaluationSpec(proto.Message): + r"""Describes the specification of the evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + Required. The search request that is used to perform the + evaluation. + + Only the following fields within SearchRequest are + supported; if any other fields are provided, an UNSUPPORTED + error will be returned: + + - [SearchRequest.serving_config][google.cloud.discoveryengine.v1beta.SearchRequest.serving_config] + - [SearchRequest.branch][google.cloud.discoveryengine.v1beta.SearchRequest.branch] + - [SearchRequest.canonical_filter][google.cloud.discoveryengine.v1beta.SearchRequest.canonical_filter] + - [SearchRequest.query_expansion_spec][google.cloud.discoveryengine.v1beta.SearchRequest.query_expansion_spec] + - [SearchRequest.spell_correction_spec][google.cloud.discoveryengine.v1beta.SearchRequest.spell_correction_spec] + - [SearchRequest.content_search_spec][google.cloud.discoveryengine.v1beta.SearchRequest.content_search_spec] + - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id] + + This field is a member of `oneof`_ ``search_spec``. + query_set_spec (google.cloud.discoveryengine_v1beta.types.Evaluation.EvaluationSpec.QuerySetSpec): + Required. The specification of the query set. + """ + + class QuerySetSpec(proto.Message): + r"""Describes the specification of the query set. + + Attributes: + sample_query_set (str): + Required. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + used for the evaluation, in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + """ + + sample_query_set: str = proto.Field( + proto.STRING, + number=1, + ) + + search_request: search_service.SearchRequest = proto.Field( + proto.MESSAGE, + number=2, + oneof="search_spec", + message=search_service.SearchRequest, + ) + query_set_spec: "Evaluation.EvaluationSpec.QuerySetSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="Evaluation.EvaluationSpec.QuerySetSpec", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_spec: EvaluationSpec = proto.Field( + proto.MESSAGE, + number=2, + message=EvaluationSpec, + ) + quality_metrics: "QualityMetrics" = proto.Field( + proto.MESSAGE, + number=3, + message="QualityMetrics", + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + message=status_pb2.Status, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=status_pb2.Status, + ) + + +class QualityMetrics(proto.Message): + r"""Describes the metrics produced by the evaluation. + + Attributes: + doc_recall (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Recall per document, at various top-k cutoff levels. + + Recall is the fraction of relevant documents retrieved out + of all relevant documents. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + If 3 out of 5 relevant documents are retrieved in the + top-5, recall@5 = 3/5 = 0.6 + doc_precision (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Precision per document, at various top-k cutoff levels. + + Precision is the fraction of retrieved documents that are + relevant. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + If 4 out of 5 retrieved documents in the top-5 are + relevant, precision@5 = 4/5 = 0.8 + doc_ndcg (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per document, + at various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + with three retrieved documents (D1, D2, D3) and binary + relevance judgements (1 for relevant, 0 for not relevant): + + Retrieved: [D3 (0), D1 (1), D2 (1)] Ideal: [D1 (1), D2 (1), + D3 (0)] + + Calculate NDCG@3 for each + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + page_recall (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Recall per page, at various top-k cutoff levels. + + Recall is the fraction of relevant pages retrieved out of + all relevant pages. + + Example (top-5): + + - For a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + if 3 out of 5 relevant pages are retrieved in the top-5, + recall@5 = 3/5 = 0.6 + page_ndcg (google.cloud.discoveryengine_v1beta.types.QualityMetrics.TopkMetrics): + Normalized discounted cumulative gain (NDCG) per page, at + various top-k cutoff levels. + + NDCG measures the ranking quality, giving higher relevance + to top results. + + Example (top-3): Suppose + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + with three retrieved pages (P1, P2, P3) and binary relevance + judgements (1 for relevant, 0 for not relevant): + + Retrieved: [P3 (0), P1 (1), P2 (1)] Ideal: [P1 (1), P2 (1), + P3 (0)] + + Calculate NDCG@3 for + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]: + \* DCG@3: 0/log2(1+1) + 1/log2(2+1) + 1/log2(3+1) = 1.13 \* + Ideal DCG@3: 1/log2(1+1) + 1/log2(2+1) + 0/log2(3+1) = 1.63 + \* NDCG@3: 1.13/1.63 = 0.693 + """ + + class TopkMetrics(proto.Message): + r"""Stores the metric values at specific top-k levels. + + Attributes: + top_1 (float): + The top-1 value. + top_3 (float): + The top-3 value. + top_5 (float): + The top-5 value. + top_10 (float): + The top-10 value. + """ + + top_1: float = proto.Field( + proto.DOUBLE, + number=1, + ) + top_3: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_5: float = proto.Field( + proto.DOUBLE, + number=3, + ) + top_10: float = proto.Field( + proto.DOUBLE, + number=4, + ) + + doc_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=1, + message=TopkMetrics, + ) + doc_precision: TopkMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=TopkMetrics, + ) + doc_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=3, + message=TopkMetrics, + ) + page_recall: TopkMetrics = proto.Field( + proto.MESSAGE, + number=4, + message=TopkMetrics, + ) + page_ndcg: TopkMetrics = proto.Field( + proto.MESSAGE, + number=5, + message=TopkMetrics, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation_service.py new file mode 100644 index 000000000000..53d0cc670cfa --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/evaluation_service.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetEvaluationRequest", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "CreateEvaluationRequest", + "CreateEvaluationMetadata", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + }, +) + + +class GetEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation] + method. + + Attributes: + name (str): + Required. Full resource name of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to access the + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]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 + [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + 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 ListEvaluationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] + method. + + Attributes: + evaluations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Evaluation]): + The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationsRequest.page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_evaluation.Evaluation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + evaluation (google.cloud.discoveryengine_v1beta.types.Evaluation): + Required. The + [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation] + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation: gcd_evaluation.Evaluation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.Evaluation, + ) + + +class CreateEvaluationMetadata(proto.Message): + r"""Metadata for + [EvaluationService.CreateEvaluation][google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation] + method. + + """ + + +class ListEvaluationResultsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation (str): + Required. The evaluation resource name, such as + ``projects/{project}/locations/{location}/evaluations/{evaluation}``. + + If the caller does not have permission to list + [EvaluationResult][] under this evaluation, regardless of + whether or not this evaluation set exists, a + ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of [EvaluationResult][] 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 + [ListEvaluationResultsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationResultsResponse.next_page_token], + received from a previous + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + evaluation: 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 ListEvaluationResultsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationResults][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults] + method. + + Attributes: + evaluation_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsResponse.EvaluationResult]): + The + [EvaluationResult][google.cloud.discoveryengine.v1beta.ListEvaluationResultsResponse.EvaluationResult]s. + next_page_token (str): + A token that can be sent as + [ListEvaluationResultsRequest.page_token][google.cloud.discoveryengine.v1beta.ListEvaluationResultsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + class EvaluationResult(proto.Message): + r"""Represents the results of an evaluation for a single + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + + Attributes: + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Output only. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + that was evaluated. + quality_metrics (google.cloud.discoveryengine_v1beta.types.QualityMetrics): + Output only. The metrics produced by the evaluation, for a + given + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + quality_metrics: gcd_evaluation.QualityMetrics = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_evaluation.QualityMetrics, + ) + + @property + def raw_page(self): + return self + + evaluation_results: MutableSequence[EvaluationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=EvaluationResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/import_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/import_config.py index 85771a9ca7cc..4eb6e1f652b5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/import_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/import_config.py @@ -23,7 +23,12 @@ from google.type import date_pb2 # type: ignore import proto # type: ignore -from google.cloud.discoveryengine_v1beta.types import completion, document, user_event +from google.cloud.discoveryengine_v1beta.types import ( + completion, + document, + sample_query, + user_event, +) __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1beta", @@ -46,6 +51,9 @@ "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", "ImportSuggestionDenyListEntriesMetadata", + "ImportSampleQueriesRequest", + "ImportSampleQueriesResponse", + "ImportSampleQueriesMetadata", }, ) @@ -1213,4 +1221,167 @@ class ImportSuggestionDenyListEntriesMetadata(proto.Message): ) +class ImportSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. + + 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.ImportSampleQueriesRequest.InlineSource): + The Inline source for sample query entries. + + 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 sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + class InlineSource(proto.Message): + r"""The inline source for + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery]): + Required. A list of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + to import. Max of 1000 items. + """ + + sample_queries: MutableSequence[sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=sample_query.SampleQuery, + ) + + 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 ImportSampleQueriesResponse(proto.Message): + r"""Response of the + [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries] + method. If the long running operation is done, this message is + returned by the google.longrunning.Operations.response field if the + operation is 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): + The desired location of errors incurred + during the Import. + """ + + 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", + ) + + +class ImportSampleQueriesMetadata(proto.Message): + r"""Metadata related to the progress of the ImportSampleQueries + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + ImportSampleQueries operation last update + time. If the operation is done, this is also the + finish time. + success_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + successfully imported. + failure_count (int): + Count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + that failed to be imported. + total_count (int): + Total count of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + that were processed. + """ + + 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, + ) + total_count: int = proto.Field( + proto.INT64, + number=5, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query.py new file mode 100644 index 000000000000..bbe4a7ebf7d6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SampleQuery", + }, +) + + +class SampleQuery(proto.Message): + r"""Sample Query captures metadata to be used for evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_entry (google.cloud.discoveryengine_v1beta.types.SampleQuery.QueryEntry): + The query entry. + + This field is a member of `oneof`_ ``content``. + name (str): + Identifier. The full resource name of the sample query, in + the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + was created at. + """ + + class QueryEntry(proto.Message): + r"""Query Entry captures metadata to be used for search + evaluation. + + Attributes: + query (str): + Required. The query. + targets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery.QueryEntry.Target]): + List of targets for the query. + """ + + class Target(proto.Message): + r"""Defines the parameters of the query's expected outcome. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Expected uri of the target. + + This field must be a UTF-8 encoded string with a length + limit of 2048 characters. + + Example of valid uris: ``https://example.com/abc``, + ``gcs://example/example.pdf``. + page_numbers (MutableSequence[int]): + Expected page numbers of the target. + + Each page number must be non negative. + score (float): + Relevance score of the target. + + This field is a member of `oneof`_ ``_score``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + page_numbers: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + score: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + query: str = proto.Field( + proto.STRING, + number=1, + ) + targets: MutableSequence["SampleQuery.QueryEntry.Target"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SampleQuery.QueryEntry.Target", + ) + + query_entry: QueryEntry = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message=QueryEntry, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_service.py new file mode 100644 index 000000000000..97b60afacdde --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_service.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSampleQueryRequest", + "ListSampleQueriesRequest", + "ListSampleQueriesResponse", + "CreateSampleQueryRequest", + "UpdateSampleQueryRequest", + "DeleteSampleQueryRequest", + }, +) + + +class GetSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.GetSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to access the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQueriesRequest(proto.Message): + r"""Request message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + + Attributes: + parent (str): + Required. The parent sample query set resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + + If the caller does not have permission to list + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + under this sample query set, regardless of whether or not + this sample query set exists, a ``PERMISSION_DENIED`` error + is returned. + page_size (int): + Maximum number of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]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 + [ListSampleQueriesResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListSampleQueriesResponse.next_page_token], + received from a previous + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + 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 ListSampleQueriesResponse(proto.Message): + r"""Response message for + [SampleQueryService.ListSampleQueries][google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries] + method. + + Attributes: + sample_queries (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuery]): + The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s. + next_page_token (str): + A token that can be sent as + [ListSampleQueriesRequest.page_token][google.cloud.discoveryengine.v1beta.ListSampleQueriesRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_queries: MutableSequence[gcd_sample_query.SampleQuery] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.CreateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sampleQuerySet}``. + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + to create. + sample_query_id (str): + Required. The ID to use for the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + which will become the final component of the + [SampleQuery.name][google.cloud.discoveryengine.v1beta.SampleQuery.name]. + + If the caller does not have permission to create the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQueryRequest.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, + ) + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query.SampleQuery, + ) + sample_query_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.UpdateSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery] + method. + + Attributes: + sample_query (google.cloud.discoveryengine_v1beta.types.SampleQuery): + Required. The simple query to update. + + If the caller does not have permission to update the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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 + imported 'simple query' to update. If not set, + will by default update all fields. + """ + + sample_query: gcd_sample_query.SampleQuery = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query.SampleQuery, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQueryRequest(proto.Message): + r"""Request message for + [SampleQueryService.DeleteSampleQuery][google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}``. + + If the caller does not have permission to delete the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuery][google.cloud.discoveryengine.v1beta.SampleQuery] + 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/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set.py new file mode 100644 index 000000000000..6890766ceefa --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "SampleQuerySet", + }, +) + + +class SampleQuerySet(proto.Message): + r"""A SampleQuerySet is the parent resource of SampleQuery, and + contains the configurations shared by all SampleQuery under it. + + Attributes: + name (str): + Identifier. The full resource name of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + in the format of + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + display_name (str): + Required. The sample query set display name. + + This field must be a UTF-8 encoded string with a + length limit of 128 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + was created at. + description (str): + The description of the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]. + """ + + 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, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py new file mode 100644 index 000000000000..16cba852249d --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/sample_query_set_service.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) + +__protobuf__ = proto.module( + package="google.cloud.discoveryengine.v1beta", + manifest={ + "GetSampleQuerySetRequest", + "ListSampleQuerySetsRequest", + "ListSampleQuerySetsResponse", + "CreateSampleQuerySetRequest", + "UpdateSampleQuerySetRequest", + "DeleteSampleQuerySetRequest", + }, +) + + +class GetSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.GetSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to access the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSampleQuerySetsRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + parent (str): + Required. The parent location resource name, such as + ``projects/{project}/locations/{location}``. + + If the caller does not have permission to list + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + under this location, regardless of whether or not this + location exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]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 + [ListSampleQuerySetsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListSampleQuerySetsResponse.next_page_token], + received from a previous + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + 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 ListSampleQuerySetsResponse(proto.Message): + r"""Response message for + [SampleQuerySetService.ListSampleQuerySets][google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets] + method. + + Attributes: + sample_query_sets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SampleQuerySet]): + The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s. + next_page_token (str): + A token that can be sent as + [ListSampleQuerySetsRequest.page_token][google.cloud.discoveryengine.v1beta.ListSampleQuerySetsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + sample_query_sets: MutableSequence[ + gcd_sample_query_set.SampleQuerySet + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.CreateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}``. + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + to create. + sample_query_set_id (str): + Required. The ID to use for the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + which will become the final component of the + [SampleQuerySet.name][google.cloud.discoveryengine.v1beta.SampleQuerySet.name]. + + If the caller does not have permission to create the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateSampleQuerySetRequest.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, + ) + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_sample_query_set.SampleQuerySet, + ) + sample_query_set_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.UpdateSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet] + method. + + Attributes: + sample_query_set (google.cloud.discoveryengine_v1beta.types.SampleQuerySet): + Required. The sample query set to update. + + If the caller does not have permission to update the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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 + imported 'sample query set' to update. If not + set, will by default update all fields. + """ + + sample_query_set: gcd_sample_query_set.SampleQuerySet = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_sample_query_set.SampleQuerySet, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSampleQuerySetRequest(proto.Message): + r"""Request message for + [SampleQuerySetService.DeleteSampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet] + method. + + Attributes: + name (str): + Required. Full resource name of + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + such as + ``projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}``. + + If the caller does not have permission to delete the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [SampleQuerySet][google.cloud.discoveryengine.v1beta.SampleQuerySet] + 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/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py index b6e2a2b40700..3565b14d22d4 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py @@ -20,6 +20,7 @@ from google.protobuf import struct_pb2 # type: ignore import proto # type: ignore +from google.cloud.discoveryengine_v1beta.types import chunk as gcd_chunk from google.cloud.discoveryengine_v1beta.types import common from google.cloud.discoveryengine_v1beta.types import document as gcd_document @@ -221,22 +222,30 @@ class SearchRequest(proto.Message): retrieval documents. This overrides [ServingConfig.ranking_expression][google.cloud.discoveryengine.v1beta.ServingConfig.ranking_expression]. The ranking expression is a single function or multiple - functions that are joint by "+". + functions that are joined by "+". - ranking_expression = function, { " + ", function }; - Supported functions: + + 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)``. + - 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. @@ -285,9 +294,8 @@ class ImageQuery(proto.Message): class DataStoreSpec(proto.Message): r"""A struct to define data stores to filter on in a search call and - configurations for those data stores. A maximum of 1 DataStoreSpec - per data_store is allowed. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. + configurations for those data stores. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. Attributes: data_store (str): @@ -311,7 +319,10 @@ class FacetSpec(proto.Message): limit (int): Maximum facet values that are returned for this facet. If unspecified, defaults to 20. The maximum allowed value is - 300. Values above 300 are coerced to 300. + 300. Values above 300 are coerced to 300. For aggregation in + healthcare search, when the [FacetKey.key] is + "healthcare_aggregation_key", the limit will be overridden + to 10,000 internally, regardless of the value set here. If this field is negative, an ``INVALID_ARGUMENT`` is returned. @@ -786,8 +797,35 @@ class ContentSearchSpec(proto.Message): 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. + search_result_mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SearchResultMode): + Specifies the search result mode. If unspecified, the search + result mode defaults to ``DOCUMENTS``. + chunk_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.ChunkSpec): + Specifies the chunk spec to be returned from the search + response. Only available if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS] """ + class SearchResultMode(proto.Enum): + r"""Specifies the search result mode. If unspecified, the search result + mode defaults to ``DOCUMENTS``. + + Values: + SEARCH_RESULT_MODE_UNSPECIFIED (0): + Default value. + DOCUMENTS (1): + Returns documents in the search result. + CHUNKS (2): + Returns chunks in the search result. Only available if the + [DataStore.DocumentProcessingConfig.chunking_config][] is + specified. + """ + SEARCH_RESULT_MODE_UNSPECIFIED = 0 + DOCUMENTS = 1 + CHUNKS = 2 + class SnippetSpec(proto.Message): r"""A specification for configuring snippets in a search response. @@ -835,9 +873,9 @@ class SummarySpec(proto.Message): At most 10 results for documents mode, or 50 for chunks mode, can be used to generate a summary. The chunks mode is used when - [SearchRequest.ContentSearchSpec.search_result_mode][] is - set to - [CHUNKS][SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS]. + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS]. include_citations (bool): Specifies whether to include citations in the summary. The default value is ``false``. @@ -1058,6 +1096,35 @@ class ExtractiveContentSpec(proto.Message): number=5, ) + class ChunkSpec(proto.Message): + r"""Specifies the chunk spec to be returned from the search response. + Only available if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS] + + Attributes: + num_previous_chunks (int): + The number of previous chunks to be returned + of the current chunk. The maximum allowed value + is 3. If not specified, no previous chunks will + be returned. + num_next_chunks (int): + The number of next chunks to be returned of + the current chunk. The maximum allowed value is + 3. If not specified, no next chunks will be + returned. + """ + + num_previous_chunks: int = proto.Field( + proto.INT32, + number=1, + ) + num_next_chunks: int = proto.Field( + proto.INT32, + number=2, + ) + snippet_spec: "SearchRequest.ContentSearchSpec.SnippetSpec" = proto.Field( proto.MESSAGE, number=1, @@ -1073,6 +1140,18 @@ class ExtractiveContentSpec(proto.Message): number=3, message="SearchRequest.ContentSearchSpec.ExtractiveContentSpec", ) + search_result_mode: "SearchRequest.ContentSearchSpec.SearchResultMode" = ( + proto.Field( + proto.ENUM, + number=4, + enum="SearchRequest.ContentSearchSpec.SearchResultMode", + ) + ) + chunk_spec: "SearchRequest.ContentSearchSpec.ChunkSpec" = proto.Field( + proto.MESSAGE, + number=5, + message="SearchRequest.ContentSearchSpec.ChunkSpec", + ) class EmbeddingSpec(proto.Message): r"""The specification that uses customized query embedding vector @@ -1285,6 +1364,11 @@ class SearchResult(proto.Message): document (google.cloud.discoveryengine_v1beta.types.Document): The document data snippet in the search response. Only fields that are marked as ``retrievable`` are populated. + chunk (google.cloud.discoveryengine_v1beta.types.Chunk): + The chunk data in the search response if the + [SearchRequest.ContentSearchSpec.search_result_mode][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.search_result_mode] + is set to + [CHUNKS][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS]. model_scores (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.DoubleList]): Google provided available scores. """ @@ -1298,6 +1382,11 @@ class SearchResult(proto.Message): number=2, message=gcd_document.Document, ) + chunk: gcd_chunk.Chunk = proto.Field( + proto.MESSAGE, + number=18, + message=gcd_chunk.Chunk, + ) model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( proto.STRING, proto.MESSAGE, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py index 0613e97d71b1..3594a4e4c065 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py @@ -119,19 +119,27 @@ class ServingConfig(proto.Message): functions that are joined by "+". - ranking_expression = function, { " + ", function }; - Supported functions: + + 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). + - 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)`. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. ServingConfig created timestamp. update_time (google.protobuf.timestamp_pb2.Timestamp): diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py new file mode 100644 index 000000000000..2bd815752a55 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_CreateEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1alpha.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1alpha.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_CreateEvaluation_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py new file mode 100644 index 000000000000..d26e760da180 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_CreateEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1alpha.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1alpha.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_CreateEvaluation_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py new file mode 100644 index 000000000000..38139c78499f --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_GetEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_GetEvaluation_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py new file mode 100644 index 000000000000..0a754ff2f188 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_GetEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_GetEvaluation_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py new file mode 100644 index 000000000000..0632a115eeed --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluationResults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation_results(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_ListEvaluationResults_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py new file mode 100644 index 000000000000..8c9d7b0c3f2e --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluationResults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluation_results(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_ListEvaluationResults_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py new file mode 100644 index 000000000000..dcb355d5674f --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluations(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_ListEvaluations_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py new file mode 100644 index 000000000000..61f24db2eb1c --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_evaluations(): + # Create a client + client = discoveryengine_v1alpha.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EvaluationService_ListEvaluations_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_async.py new file mode 100644 index 000000000000..b4267dbadc9e --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_CreateSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = await client.create_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_CreateSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_sync.py new file mode 100644 index 000000000000..421b4887ec0f --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_CreateSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = client.create_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_CreateSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_async.py new file mode 100644 index 000000000000..327d2c887227 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_DeleteSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query(request=request) + + +# [END discoveryengine_v1alpha_generated_SampleQueryService_DeleteSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_sync.py new file mode 100644 index 000000000000..17f926f4abbb --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_DeleteSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query(request=request) + + +# [END discoveryengine_v1alpha_generated_SampleQueryService_DeleteSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_async.py new file mode 100644 index 000000000000..41b01ca10857 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_GetSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_GetSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_sync.py new file mode 100644 index 000000000000..4d7bb6bab0b0 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_GetSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_GetSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py new file mode 100644 index 000000000000..8f3dc14c4ebf --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ImportSampleQueries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_ImportSampleQueries_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py new file mode 100644 index 000000000000..a392ecb21514 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ImportSampleQueries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_ImportSampleQueries_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_async.py new file mode 100644 index 000000000000..c0a88f94bad0 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ListSampleQueries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_ListSampleQueries_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_sync.py new file mode 100644 index 000000000000..501aa6f4cfce --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ListSampleQueries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_queries(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_ListSampleQueries_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_async.py new file mode 100644 index 000000000000..9b3ecdeb4150 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_UpdateSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = await client.update_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_UpdateSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_sync.py new file mode 100644 index 000000000000..439a332a579a --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_UpdateSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query(): + # Create a client + client = discoveryengine_v1alpha.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1alpha.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1alpha.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = client.update_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQueryService_UpdateSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_async.py new file mode 100644 index 000000000000..85673d667265 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_CreateSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = await client.create_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_CreateSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_sync.py new file mode 100644 index 000000000000..ab42871d718a --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_CreateSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = client.create_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_CreateSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_async.py new file mode 100644 index 000000000000..ef4ae3835520 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_DeleteSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query_set(request=request) + + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_DeleteSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_sync.py new file mode 100644 index 000000000000..43227f63bdcc --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_DeleteSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query_set(request=request) + + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_DeleteSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py new file mode 100644 index 000000000000..dc0dc5d419e1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_GetSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_GetSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py new file mode 100644 index 000000000000..054e65d5dd65 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_GetSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_GetSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py new file mode 100644 index 000000000000..6a1e6297f781 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQuerySets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_ListSampleQuerySets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_sets(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_ListSampleQuerySets_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py new file mode 100644 index 000000000000..4bbb210cdaf6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQuerySets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_ListSampleQuerySets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_sets(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_ListSampleQuerySets_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py new file mode 100644 index 000000000000..c8fa7e0b13cd --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_UpdateSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = await client.update_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_UpdateSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_sync.py new file mode 100644 index 000000000000..e72855cd4e0b --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_UpdateSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when 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_sample_query_set(): + # Create a client + client = discoveryengine_v1alpha.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1alpha.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = client.update_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SampleQuerySetService_UpdateSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_async.py new file mode 100644 index 000000000000..d2b785341fb8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_CreateEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1beta.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_CreateEvaluation_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_sync.py new file mode 100644 index 000000000000..94e991f82b53 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_create_evaluation_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_CreateEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = discoveryengine_v1beta.Evaluation() + evaluation.evaluation_spec.search_request.serving_config = "serving_config_value" + evaluation.evaluation_spec.query_set_spec.sample_query_set = "sample_query_set_value" + + request = discoveryengine_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + operation = client.create_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_CreateEvaluation_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_async.py new file mode 100644 index 000000000000..f64e9467234f --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_GetEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_GetEvaluation_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_sync.py new file mode 100644 index 000000000000..3c7150aa88e2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_get_evaluation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_GetEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_GetEvaluation_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_async.py new file mode 100644 index 000000000000..ad70df4a8169 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluationResults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation_results(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_ListEvaluationResults_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_sync.py new file mode 100644 index 000000000000..c18e2703ad84 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluationResults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluation_results(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationResultsRequest( + evaluation="evaluation_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_ListEvaluationResults_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_async.py new file mode 100644 index 000000000000..efdac433d252 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluations(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_ListEvaluations_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_sync.py new file mode 100644 index 000000000000..87486f40eda8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_evaluation_service_list_evaluations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_EvaluationService_ListEvaluations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_evaluations(): + # Create a client + client = discoveryengine_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_EvaluationService_ListEvaluations_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py new file mode 100644 index 000000000000..438cb69816ee --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_CreateSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = await client.create_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py new file mode 100644 index 000000000000..abf095eb008b --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_CreateSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.CreateSampleQueryRequest( + parent="parent_value", + sample_query=sample_query, + sample_query_id="sample_query_id_value", + ) + + # Make the request + response = client.create_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py new file mode 100644 index 000000000000..7848b7d07668 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_DeleteSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query(request=request) + + +# [END discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py new file mode 100644 index 000000000000..d2bdb98d4dc2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_DeleteSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query(request=request) + + +# [END discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py new file mode 100644 index 000000000000..dbbcb8e50366 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_GetSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py new file mode 100644 index 000000000000..e63d5ec2b052 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_GetSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py new file mode 100644 index 000000000000..bbe45421162a --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ImportSampleQueries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1beta.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py new file mode 100644 index 000000000000..a8baeedaadee --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ImportSampleQueries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.sample_queries.query_entry.query = "query_value" + + request = discoveryengine_v1beta.ImportSampleQueriesRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_sample_queries(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py new file mode 100644 index 000000000000..2363e972e0f7 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ListSampleQueries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py new file mode 100644 index 000000000000..fe163cdc04f6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_ListSampleQueries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_queries(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py new file mode 100644 index 000000000000..98a4960de08d --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_UpdateSampleQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceAsyncClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = await client.update_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py new file mode 100644 index 000000000000..5eae6a444c53 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQueryService_UpdateSampleQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query(): + # Create a client + client = discoveryengine_v1beta.SampleQueryServiceClient() + + # Initialize request argument(s) + sample_query = discoveryengine_v1beta.SampleQuery() + sample_query.query_entry.query = "query_value" + + request = discoveryengine_v1beta.UpdateSampleQueryRequest( + sample_query=sample_query, + ) + + # Make the request + response = client.update_sample_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py new file mode 100644 index 000000000000..6d317a736da3 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_CreateSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = await client.create_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py new file mode 100644 index 000000000000..106660fae7e3 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_CreateSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set=sample_query_set, + sample_query_set_id="sample_query_set_id_value", + ) + + # Make the request + response = client.create_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py new file mode 100644 index 000000000000..461bcb335130 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_DeleteSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + await client.delete_sample_query_set(request=request) + + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py new file mode 100644 index 000000000000..7d7cc2862c32 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_DeleteSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + client.delete_sample_query_set(request=request) + + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py new file mode 100644 index 000000000000..293954c1c334 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_GetSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py new file mode 100644 index 000000000000..b9fba68f14eb --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_GetSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSampleQuerySetRequest( + name="name_value", + ) + + # Make the request + response = client.get_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py new file mode 100644 index 000000000000..ab1c1182186e --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQuerySets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_ListSampleQuerySets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_sets(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py new file mode 100644 index 000000000000..e3cf5b9009b0 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSampleQuerySets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_ListSampleQuerySets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_sets(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSampleQuerySetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sample_query_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py new file mode 100644 index 000000000000..e54a21a56bca --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_UpdateSampleQuerySet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceAsyncClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = await client.update_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py new file mode 100644 index 000000000000..1152ed8e56ee --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSampleQuerySet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications 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_SampleQuerySetService_UpdateSampleQuerySet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints 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_sample_query_set(): + # Create a client + client = discoveryengine_v1beta.SampleQuerySetServiceClient() + + # Initialize request argument(s) + sample_query_set = discoveryengine_v1beta.SampleQuerySet() + sample_query_set.display_name = "display_name_value" + + request = discoveryengine_v1beta.UpdateSampleQuerySetRequest( + sample_query_set=sample_query_set, + ) + + # Make the request + response = client.update_sample_query_set(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json index 96d437f00f2e..69944fc7ce8a 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.11.14" + "version": "0.1.0" }, "snippets": [ { 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 894707e20001..e6c771a6e5c7 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 @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.11.14" + "version": "0.1.0" }, "snippets": [ { @@ -7961,22 +7961,30 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceAsyncClient", - "shortName": "GroundedGenerationServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceAsyncClient.check_grounding", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient.create_evaluation", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService.CheckGrounding", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService", - "shortName": "GroundedGenerationService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "CheckGrounding" + "shortName": "CreateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.discoveryengine_v1alpha.types.Evaluation" }, { "name": "retry", @@ -7991,22 +7999,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingResponse", - "shortName": "check_grounding" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_evaluation" }, - "description": "Sample for CheckGrounding", - "file": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_async.py", + "description": "Sample for CreateEvaluation", + "file": "discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_GroundedGenerationService_CheckGrounding_async", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_CreateEvaluation_async", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -8016,43 +8024,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_async.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceClient", - "shortName": "GroundedGenerationServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceClient.check_grounding", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient.create_evaluation", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService.CheckGrounding", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.CreateEvaluation", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService", - "shortName": "GroundedGenerationService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "CheckGrounding" + "shortName": "CreateEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.discoveryengine_v1alpha.types.Evaluation" }, { "name": "retry", @@ -8067,22 +8083,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingResponse", - "shortName": "check_grounding" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_evaluation" }, - "description": "Sample for CheckGrounding", - "file": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_sync.py", + "description": "Sample for CreateEvaluation", + "file": "discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_GroundedGenerationService_CheckGrounding_sync", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_CreateEvaluation_sync", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -8092,44 +8108,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_sync.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_create_evaluation_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", - "shortName": "ProjectServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.get_project", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient.get_evaluation", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.GetProject", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "GetProject" + "shortName": "GetEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetProjectRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetEvaluationRequest" }, { "name": "name", @@ -8148,14 +8164,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", - "shortName": "get_project" + "resultType": "google.cloud.discoveryengine_v1alpha.types.Evaluation", + "shortName": "get_evaluation" }, - "description": "Sample for GetProject", - "file": "discoveryengine_v1alpha_generated_project_service_get_project_async.py", + "description": "Sample for GetEvaluation", + "file": "discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_GetProject_async", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_GetEvaluation_async", "segments": [ { "end": 51, @@ -8188,28 +8204,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_get_project_async.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", - "shortName": "ProjectServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.get_project", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient.get_evaluation", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.GetProject", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.GetEvaluation", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "GetProject" + "shortName": "GetEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetProjectRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetEvaluationRequest" }, { "name": "name", @@ -8228,14 +8244,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", - "shortName": "get_project" + "resultType": "google.cloud.discoveryengine_v1alpha.types.Evaluation", + "shortName": "get_evaluation" }, - "description": "Sample for GetProject", - "file": "discoveryengine_v1alpha_generated_project_service_get_project_sync.py", + "description": "Sample for GetEvaluation", + "file": "discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_GetProject_sync", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_GetEvaluation_sync", "segments": [ { "end": 51, @@ -8268,32 +8284,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_get_project_sync.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_get_evaluation_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", - "shortName": "ProjectServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient.list_evaluation_results", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "ProvisionProject" + "shortName": "ListEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ProvisionProjectRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsRequest" }, { - "name": "name", + "name": "evaluation", "type": "str" }, { @@ -8309,22 +8325,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager", + "shortName": "list_evaluation_results" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1alpha_generated_project_service_provision_project_async.py", + "description": "Sample for ListEvaluationResults", + "file": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ProvisionProject_async", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_ListEvaluationResults_async", "segments": [ { - "end": 57, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8334,46 +8350,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_provision_project_async.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", - "shortName": "ProjectServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient.list_evaluation_results", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluationResults", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "ProvisionProject" + "shortName": "ListEvaluationResults" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ProvisionProjectRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListEvaluationResultsRequest" }, { - "name": "name", + "name": "evaluation", "type": "str" }, { @@ -8389,22 +8405,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationResultsPager", + "shortName": "list_evaluation_results" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1alpha_generated_project_service_provision_project_sync.py", + "description": "Sample for ListEvaluationResults", + "file": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ProvisionProject_sync", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_ListEvaluationResults_sync", "segments": [ { - "end": 57, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8414,59 +8430,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_provision_project_sync.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluation_results_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", - "shortName": "ProjectServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.report_consent_change", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceAsyncClient.list_evaluations", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ReportConsentChange", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "ReportConsentChange" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest" - }, - { - "name": "consent_change_action", - "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest.ConsentChangeAction" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "service_term_id", - "type": "str" + "type": "google.cloud.discoveryengine_v1alpha.types.ListEvaluationsRequest" }, { - "name": "service_term_version", + "name": "parent", "type": "str" }, { @@ -8482,22 +8486,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", - "shortName": "report_consent_change" + "resultType": "google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" }, - "description": "Sample for ReportConsentChange", - "file": "discoveryengine_v1alpha_generated_project_service_report_consent_change_async.py", + "description": "Sample for ListEvaluations", + "file": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ReportConsentChange_async", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_ListEvaluations_async", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8507,58 +8511,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_report_consent_change_async.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", - "shortName": "ProjectServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.report_consent_change", + "fullName": "google.cloud.discoveryengine_v1alpha.EvaluationServiceClient.list_evaluations", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ReportConsentChange", + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1alpha.EvaluationService", + "shortName": "EvaluationService" }, - "shortName": "ReportConsentChange" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest" - }, - { - "name": "consent_change_action", - "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest.ConsentChangeAction" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "service_term_id", - "type": "str" + "type": "google.cloud.discoveryengine_v1alpha.types.ListEvaluationsRequest" }, { - "name": "service_term_version", + "name": "parent", "type": "str" }, { @@ -8574,22 +8566,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", - "shortName": "report_consent_change" + "resultType": "google.cloud.discoveryengine_v1alpha.services.evaluation_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" }, - "description": "Sample for ReportConsentChange", - "file": "discoveryengine_v1alpha_generated_project_service_report_consent_change_sync.py", + "description": "Sample for ListEvaluations", + "file": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ReportConsentChange_sync", + "regionTag": "discoveryengine_v1alpha_generated_EvaluationService_ListEvaluations_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8599,44 +8591,780 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_project_service_report_consent_change_sync.py" + "title": "discoveryengine_v1alpha_generated_evaluation_service_list_evaluations_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceAsyncClient", - "shortName": "RankServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceAsyncClient", + "shortName": "GroundedGenerationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceAsyncClient.rank", + "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceAsyncClient.check_grounding", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService.CheckGrounding", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService", + "shortName": "GroundedGenerationService" }, - "shortName": "Rank" + "shortName": "CheckGrounding" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RankRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingRequest" + }, + { + "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.CheckGroundingResponse", + "shortName": "check_grounding" + }, + "description": "Sample for CheckGrounding", + "file": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_GroundedGenerationService_CheckGrounding_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_grounded_generation_service_check_grounding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceClient", + "shortName": "GroundedGenerationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.GroundedGenerationServiceClient.check_grounding", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService.CheckGrounding", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.GroundedGenerationService", + "shortName": "GroundedGenerationService" + }, + "shortName": "CheckGrounding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CheckGroundingRequest" + }, + { + "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.CheckGroundingResponse", + "shortName": "check_grounding" + }, + "description": "Sample for CheckGrounding", + "file": "discoveryengine_v1alpha_generated_grounded_generation_service_check_grounding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_GroundedGenerationService_CheckGrounding_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_grounded_generation_service_check_grounding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", + "shortName": "ProjectServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.get_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.GetProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "GetProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", + "shortName": "get_project" + }, + "description": "Sample for GetProject", + "file": "discoveryengine_v1alpha_generated_project_service_get_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_GetProject_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_project_service_get_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", + "shortName": "ProjectServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.get_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.GetProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "GetProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Project", + "shortName": "get_project" + }, + "description": "Sample for GetProject", + "file": "discoveryengine_v1alpha_generated_project_service_get_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_GetProject_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_project_service_get_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", + "shortName": "ProjectServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ProvisionProjectRequest" + }, + { + "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": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1alpha_generated_project_service_provision_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ProvisionProject_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_project_service_provision_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", + "shortName": "ProjectServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ProvisionProjectRequest" + }, + { + "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": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1alpha_generated_project_service_provision_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ProvisionProject_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_project_service_provision_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient", + "shortName": "ProjectServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceAsyncClient.report_consent_change", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ReportConsentChange", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ReportConsentChange" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest" + }, + { + "name": "consent_change_action", + "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest.ConsentChangeAction" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "service_term_id", + "type": "str" + }, + { + "name": "service_term_version", + "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.Project", + "shortName": "report_consent_change" + }, + "description": "Sample for ReportConsentChange", + "file": "discoveryengine_v1alpha_generated_project_service_report_consent_change_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ReportConsentChange_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_project_service_report_consent_change_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient", + "shortName": "ProjectServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ProjectServiceClient.report_consent_change", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService.ReportConsentChange", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ReportConsentChange" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest" + }, + { + "name": "consent_change_action", + "type": "google.cloud.discoveryengine_v1alpha.types.ReportConsentChangeRequest.ConsentChangeAction" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "service_term_id", + "type": "str" + }, + { + "name": "service_term_version", + "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.Project", + "shortName": "report_consent_change" + }, + "description": "Sample for ReportConsentChange", + "file": "discoveryengine_v1alpha_generated_project_service_report_consent_change_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ProjectService_ReportConsentChange_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_project_service_report_consent_change_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceAsyncClient", + "shortName": "RankServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceAsyncClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RankRequest" + }, + { + "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.RankResponse", + "shortName": "rank" + }, + "description": "Sample for Rank", + "file": "discoveryengine_v1alpha_generated_rank_service_rank_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_RankService_Rank_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_rank_service_rank_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceClient", + "shortName": "RankServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RankRequest" }, { "name": "retry", @@ -8654,11 +9382,1553 @@ "resultType": "google.cloud.discoveryengine_v1alpha.types.RankResponse", "shortName": "rank" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1alpha_generated_rank_service_rank_async.py", + "description": "Sample for Rank", + "file": "discoveryengine_v1alpha_generated_rank_service_rank_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_RankService_Rank_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_rank_service_rank_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.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuery" + }, + { + "name": "sample_query_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.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_CreateSampleQuery_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_sample_query_service_create_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuery" + }, + { + "name": "sample_query_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.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_create_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_CreateSampleQuery_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_sample_query_service_create_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSampleQueryRequest" + }, + { + "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_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_DeleteSampleQuery_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_sample_query_service_delete_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSampleQueryRequest" + }, + { + "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_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_delete_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_DeleteSampleQuery_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_sample_query_service_delete_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.get_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "GetSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSampleQueryRequest" + }, + { + "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.SampleQuery", + "shortName": "get_sample_query" + }, + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_GetSampleQuery_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_sample_query_service_get_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.get_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.GetSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "GetSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSampleQueryRequest" + }, + { + "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.SampleQuery", + "shortName": "get_sample_query" + }, + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_get_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_GetSampleQuery_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_sample_query_service_get_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.import_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ImportSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportSampleQueriesRequest" + }, + { + "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_sample_queries" + }, + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_ImportSampleQueries_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.import_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ImportSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportSampleQueriesRequest" + }, + { + "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_sample_queries" + }, + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_ImportSampleQueries_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_sample_query_service_import_sample_queries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.list_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ListSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesRequest" + }, + { + "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.sample_query_service.pagers.ListSampleQueriesAsyncPager", + "shortName": "list_sample_queries" + }, + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_ListSampleQueries_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_sample_query_service_list_sample_queries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.list_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.ListSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ListSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListSampleQueriesRequest" + }, + { + "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.sample_query_service.pagers.ListSampleQueriesPager", + "shortName": "list_sample_queries" + }, + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1alpha_generated_sample_query_service_list_sample_queries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_ListSampleQueries_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_sample_query_service_list_sample_queries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceAsyncClient.update_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "UpdateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSampleQueryRequest" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuery" + }, + { + "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.SampleQuery", + "shortName": "update_sample_query" + }, + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_UpdateSampleQuery_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_sample_query_service_update_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQueryServiceClient.update_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService.UpdateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "UpdateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSampleQueryRequest" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuery" + }, + { + "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.SampleQuery", + "shortName": "update_sample_query" + }, + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1alpha_generated_sample_query_service_update_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQueryService_UpdateSampleQuery_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_sample_query_service_update_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient.create_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "CreateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuerySet" + }, + { + "name": "sample_query_set_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.SampleQuerySet", + "shortName": "create_sample_query_set" + }, + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_CreateSampleQuerySet_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_sample_query_set_service_create_sample_query_set_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient.create_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.CreateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "CreateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuerySet" + }, + { + "name": "sample_query_set_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.SampleQuerySet", + "shortName": "create_sample_query_set" + }, + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_create_sample_query_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_CreateSampleQuerySet_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_sample_query_set_service_create_sample_query_set_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient.delete_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "DeleteSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSampleQuerySetRequest" + }, + { + "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_sample_query_set" + }, + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_DeleteSampleQuerySet_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_sample_query_set_service_delete_sample_query_set_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient.delete_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.DeleteSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "DeleteSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSampleQuerySetRequest" + }, + { + "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_sample_query_set" + }, + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_delete_sample_query_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_DeleteSampleQuerySet_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_sample_query_set_service_delete_sample_query_set_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient.get_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "GetSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSampleQuerySetRequest" + }, + { + "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.SampleQuerySet", + "shortName": "get_sample_query_set" + }, + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RankService_Rank_async", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_GetSampleQuerySet_async", "segments": [ { "end": 51, @@ -8691,28 +10961,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_rank_service_rank_async.py" + "title": "discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceClient", - "shortName": "RankServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.RankServiceClient.rank", + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient.get_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.GetSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Rank" + "shortName": "GetSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RankRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetSampleQuerySetRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -8727,14 +11001,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.RankResponse", - "shortName": "rank" + "resultType": "google.cloud.discoveryengine_v1alpha.types.SampleQuerySet", + "shortName": "get_sample_query_set" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1alpha_generated_rank_service_rank_sync.py", + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RankService_Rank_sync", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_GetSampleQuerySet_sync", "segments": [ { "end": 51, @@ -8767,29 +11041,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_rank_service_rank_sync.py" + "title": "discoveryengine_v1alpha_generated_sample_query_set_service_get_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient", - "shortName": "RecommendationServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient.recommend", + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Recommend" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -8804,22 +11082,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_async", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_ListSampleQuerySets_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8829,43 +11107,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py" + "title": "discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient", - "shortName": "RecommendationServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient.recommend", + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.ListSampleQuerySets", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Recommend" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListSampleQuerySetsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -8880,22 +11162,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.pagers.ListSampleQuerySetsPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_ListSampleQuerySets_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8905,22 +11187,191 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, { "end": 53, - "start": 51, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_sample_query_set_service_list_sample_query_sets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceAsyncClient.update_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "UpdateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSampleQuerySetRequest" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuerySet" + }, + { + "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.SampleQuerySet", + "shortName": "update_sample_query_set" + }, + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_UpdateSampleQuerySet_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": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py" + "title": "discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SampleQuerySetServiceClient.update_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService.UpdateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "UpdateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSampleQuerySetRequest" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1alpha.types.SampleQuerySet" + }, + { + "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.SampleQuerySet", + "shortName": "update_sample_query_set" + }, + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1alpha_generated_sample_query_set_service_update_sample_query_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SampleQuerySetService_UpdateSampleQuerySet_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_sample_query_set_service_update_sample_query_set_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json index aece581a0e06..1bcb214a5ae3 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.11.14" + "version": "0.1.0" }, "snippets": [ { @@ -6676,6 +6676,658 @@ ], "title": "discoveryengine_v1beta_generated_engine_service_update_engine_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient.create_evaluation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.discoveryengine_v1beta.types.Evaluation" + }, + { + "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_evaluation" + }, + "description": "Sample for CreateEvaluation", + "file": "discoveryengine_v1beta_generated_evaluation_service_create_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_CreateEvaluation_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_evaluation_service_create_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient.create_evaluation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.CreateEvaluation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.discoveryengine_v1beta.types.Evaluation" + }, + { + "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_evaluation" + }, + "description": "Sample for CreateEvaluation", + "file": "discoveryengine_v1beta_generated_evaluation_service_create_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_CreateEvaluation_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_evaluation_service_create_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient.get_evaluation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetEvaluationRequest" + }, + { + "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.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "discoveryengine_v1beta_generated_evaluation_service_get_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_GetEvaluation_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_evaluation_service_get_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient.get_evaluation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.GetEvaluation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetEvaluationRequest" + }, + { + "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.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "discoveryengine_v1beta_generated_evaluation_service_get_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_GetEvaluation_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_evaluation_service_get_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient.list_evaluation_results", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsRequest" + }, + { + "name": "evaluation", + "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.evaluation_service.pagers.ListEvaluationResultsAsyncPager", + "shortName": "list_evaluation_results" + }, + "description": "Sample for ListEvaluationResults", + "file": "discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_ListEvaluationResults_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_evaluation_service_list_evaluation_results_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient.list_evaluation_results", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluationResults", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListEvaluationResultsRequest" + }, + { + "name": "evaluation", + "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.evaluation_service.pagers.ListEvaluationResultsPager", + "shortName": "list_evaluation_results" + }, + "description": "Sample for ListEvaluationResults", + "file": "discoveryengine_v1beta_generated_evaluation_service_list_evaluation_results_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_ListEvaluationResults_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_evaluation_service_list_evaluation_results_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceAsyncClient.list_evaluations", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListEvaluationsRequest" + }, + { + "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.evaluation_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "discoveryengine_v1beta_generated_evaluation_service_list_evaluations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_ListEvaluations_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_evaluation_service_list_evaluations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.EvaluationServiceClient.list_evaluations", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListEvaluationsRequest" + }, + { + "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.evaluation_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "discoveryengine_v1beta_generated_evaluation_service_list_evaluations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_EvaluationService_ListEvaluations_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_evaluation_service_list_evaluations_sync.py" + }, { "canonical": true, "clientMethod": { @@ -6684,19 +7336,1796 @@ "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient", "shortName": "GroundedGenerationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient.check_grounding", + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient.check_grounding", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" + }, + "shortName": "CheckGrounding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CheckGroundingRequest" + }, + { + "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.CheckGroundingResponse", + "shortName": "check_grounding" + }, + "description": "Sample for CheckGrounding", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_CheckGrounding_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_grounded_generation_service_check_grounding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient", + "shortName": "GroundedGenerationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient.check_grounding", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" + }, + "shortName": "CheckGrounding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CheckGroundingRequest" + }, + { + "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.CheckGroundingResponse", + "shortName": "check_grounding" + }, + "description": "Sample for CheckGrounding", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_CheckGrounding_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_grounded_generation_service_check_grounding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient", + "shortName": "ProjectServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + }, + { + "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": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1beta_generated_project_service_provision_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_project_service_provision_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient", + "shortName": "ProjectServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + }, + { + "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": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient", + "shortName": "RankServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + }, + { + "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.RankResponse", + "shortName": "rank" + }, + "description": "Sample for Rank", + "file": "discoveryengine_v1beta_generated_rank_service_rank_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_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_rank_service_rank_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient", + "shortName": "RankServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + }, + { + "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.RankResponse", + "shortName": "rank" + }, + "description": "Sample for Rank", + "file": "discoveryengine_v1beta_generated_rank_service_rank_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_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_rank_service_rank_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.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "sample_query_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.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_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_sample_query_service_create_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "sample_query_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.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_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_sample_query_service_create_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + }, + { + "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_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_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_sample_query_service_delete_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + }, + { + "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_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_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_sample_query_service_delete_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.get_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "GetSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + }, + { + "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.SampleQuery", + "shortName": "get_sample_query" + }, + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_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_sample_query_service_get_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.get_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "GetSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + }, + { + "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.SampleQuery", + "shortName": "get_sample_query" + }, + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_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_sample_query_service_get_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.import_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ImportSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" + }, + { + "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_sample_queries" + }, + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.import_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ImportSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" + }, + { + "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_sample_queries" + }, + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.list_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ListSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" + }, + { + "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.sample_query_service.pagers.ListSampleQueriesAsyncPager", + "shortName": "list_sample_queries" + }, + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_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_sample_query_service_list_sample_queries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.list_sample_queries", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "ListSampleQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" + }, + { + "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.sample_query_service.pagers.ListSampleQueriesPager", + "shortName": "list_sample_queries" + }, + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_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_sample_query_service_list_sample_queries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.update_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "UpdateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "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.SampleQuery", + "shortName": "update_sample_query" + }, + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_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_v1beta_generated_sample_query_service_update_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.update_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "UpdateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "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.SampleQuery", + "shortName": "update_sample_query" + }, + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_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_v1beta_generated_sample_query_service_update_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.create_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "CreateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "sample_query_set_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.SampleQuerySet", + "shortName": "create_sample_query_set" + }, + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_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_sample_query_set_service_create_sample_query_set_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.create_sample_query_set", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" + }, + "shortName": "CreateSampleQuerySet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "sample_query_set_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.SampleQuerySet", + "shortName": "create_sample_query_set" + }, + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_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_sample_query_set_service_create_sample_query_set_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.delete_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", - "shortName": "GroundedGenerationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "CheckGrounding" + "shortName": "DeleteSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CheckGroundingRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -6711,22 +9140,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse", - "shortName": "check_grounding" + "shortName": "delete_sample_query_set" }, - "description": "Sample for CheckGrounding", - "file": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_async.py", + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_CheckGrounding_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -6741,38 +9169,40 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient", - "shortName": "GroundedGenerationServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient.check_grounding", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.delete_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.CheckGrounding", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", - "shortName": "GroundedGenerationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "CheckGrounding" + "shortName": "DeleteSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CheckGroundingRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -6787,22 +9217,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse", - "shortName": "check_grounding" + "shortName": "delete_sample_query_set" }, - "description": "Sample for CheckGrounding", - "file": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_sync.py", + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_CheckGrounding_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -6817,39 +9246,37 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_grounded_generation_service_check_grounding_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient", - "shortName": "ProjectServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.get_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ProvisionProject" + "shortName": "GetSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" }, { "name": "name", @@ -6868,22 +9295,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "get_sample_query_set" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1beta_generated_project_service_provision_project_async.py", + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_async", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6893,43 +9320,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_project_service_provision_project_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient", - "shortName": "ProjectServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.get_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ProvisionProject" + "shortName": "GetSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" }, { "name": "name", @@ -6948,22 +9375,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "get_sample_query_set" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py", + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6973,44 +9400,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient", - "shortName": "RankServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient.rank", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Rank" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7025,22 +9456,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", - "shortName": "rank" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1beta_generated_rank_service_rank_async.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7060,33 +9491,37 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_rank_service_rank_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient", - "shortName": "RankServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient.rank", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Rank" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7101,22 +9536,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", - "shortName": "rank" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1beta_generated_rank_service_rank_sync.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7136,34 +9571,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_rank_service_rank_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient", - "shortName": "RecommendationServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient.recommend", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.update_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Recommend" + "shortName": "UpdateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7178,22 +9621,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "update_sample_query_set" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py", + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_async", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -7203,43 +9646,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient", - "shortName": "RecommendationServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient.recommend", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.update_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "Recommend" + "shortName": "UpdateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7254,22 +9705,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "update_sample_query_set" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py", + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_sync", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -7279,22 +9730,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_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 67511a5f2831..d5a01a5ceefe 100644 --- a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py +++ b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py @@ -51,6 +51,9 @@ class discoveryengineCallTransformer(cst.CSTTransformer): '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_evaluation': ('parent', 'evaluation', ), + 'create_sample_query': ('parent', 'sample_query', 'sample_query_id', ), + 'create_sample_query_set': ('parent', 'sample_query_set', 'sample_query_set_id', ), 'create_schema': ('parent', 'schema', 'schema_id', ), 'create_session': ('parent', 'session', ), 'create_target_site': ('parent', 'target_site', ), @@ -59,6 +62,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'delete_data_store': ('name', ), 'delete_document': ('name', ), 'delete_engine': ('name', ), + 'delete_sample_query': ('name', ), + 'delete_sample_query_set': ('name', ), 'delete_schema': ('name', ), 'delete_session': ('name', ), 'delete_target_site': ('name', ), @@ -75,14 +80,18 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'get_document': ('name', ), 'get_document_processing_config': ('name', ), 'get_engine': ('name', ), + 'get_evaluation': ('name', ), 'get_processed_document': ('name', 'processed_document_type', 'processed_document_format', ), 'get_project': ('name', ), + 'get_sample_query': ('name', ), + 'get_sample_query_set': ('name', ), 'get_schema': ('name', ), 'get_serving_config': ('name', ), 'get_session': ('name', ), 'get_site_search_engine': ('name', ), 'get_target_site': ('name', ), 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'fhir_store_source', 'spanner_source', 'cloud_sql_source', 'firestore_source', 'bigtable_source', 'error_config', 'reconciliation_mode', 'update_mask', 'auto_generate_ids', 'id_field', ), + 'import_sample_queries': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'import_suggestion_deny_list_entries': ('parent', 'inline_source', 'gcs_source', ), 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'list_chunks': ('parent', 'page_size', 'page_token', ), @@ -92,6 +101,10 @@ class discoveryengineCallTransformer(cst.CSTTransformer): '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_evaluation_results': ('evaluation', 'page_size', 'page_token', ), + 'list_evaluations': ('parent', 'page_size', 'page_token', ), + 'list_sample_queries': ('parent', 'page_size', 'page_token', ), + 'list_sample_query_sets': ('parent', 'page_size', 'page_token', ), 'list_schemas': ('parent', 'page_size', 'page_token', ), 'list_serving_configs': ('parent', 'page_size', 'page_token', ), 'list_sessions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), @@ -116,6 +129,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'update_document': ('document', 'allow_missing', 'update_mask', ), 'update_document_processing_config': ('document_processing_config', 'update_mask', ), 'update_engine': ('engine', 'update_mask', ), + 'update_sample_query': ('sample_query', 'update_mask', ), + 'update_sample_query_set': ('sample_query_set', 'update_mask', ), 'update_schema': ('schema', 'allow_missing', ), 'update_serving_config': ('serving_config', 'update_mask', ), 'update_session': ('session', 'update_mask', ), diff --git a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py index 85127db6149f..60dd01e64dd8 100644 --- a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py +++ b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py @@ -51,6 +51,9 @@ class discoveryengineCallTransformer(cst.CSTTransformer): '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_evaluation': ('parent', 'evaluation', ), + 'create_sample_query': ('parent', 'sample_query', 'sample_query_id', ), + 'create_sample_query_set': ('parent', 'sample_query_set', 'sample_query_set_id', ), 'create_schema': ('parent', 'schema', 'schema_id', ), 'create_session': ('parent', 'session', ), 'create_target_site': ('parent', 'target_site', ), @@ -59,6 +62,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'delete_data_store': ('name', ), 'delete_document': ('name', ), 'delete_engine': ('name', ), + 'delete_sample_query': ('name', ), + 'delete_sample_query_set': ('name', ), 'delete_schema': ('name', ), 'delete_session': ('name', ), 'delete_target_site': ('name', ), @@ -71,12 +76,16 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'get_data_store': ('name', ), 'get_document': ('name', ), 'get_engine': ('name', ), + 'get_evaluation': ('name', ), + 'get_sample_query': ('name', ), + 'get_sample_query_set': ('name', ), 'get_schema': ('name', ), 'get_serving_config': ('name', ), 'get_session': ('name', ), 'get_site_search_engine': ('name', ), 'get_target_site': ('name', ), 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'fhir_store_source', 'spanner_source', 'cloud_sql_source', 'firestore_source', 'bigtable_source', 'error_config', 'reconciliation_mode', 'update_mask', 'auto_generate_ids', 'id_field', ), + 'import_sample_queries': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'import_suggestion_deny_list_entries': ('parent', 'inline_source', 'gcs_source', ), 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'list_controls': ('parent', 'page_size', 'page_token', 'filter', ), @@ -85,6 +94,10 @@ class discoveryengineCallTransformer(cst.CSTTransformer): '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_evaluation_results': ('evaluation', 'page_size', 'page_token', ), + 'list_evaluations': ('parent', 'page_size', 'page_token', ), + 'list_sample_queries': ('parent', 'page_size', 'page_token', ), + 'list_sample_query_sets': ('parent', 'page_size', 'page_token', ), 'list_schemas': ('parent', 'page_size', 'page_token', ), 'list_serving_configs': ('parent', 'page_size', 'page_token', ), 'list_sessions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), @@ -105,6 +118,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'update_data_store': ('data_store', 'update_mask', ), 'update_document': ('document', 'allow_missing', 'update_mask', ), 'update_engine': ('engine', 'update_mask', ), + 'update_sample_query': ('sample_query', 'update_mask', ), + 'update_sample_query_set': ('sample_query_set', 'update_mask', ), 'update_schema': ('schema', 'allow_missing', ), 'update_serving_config': ('serving_config', 'update_mask', ), 'update_session': ('session', 'update_mask', ), diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py new file mode 100644 index 000000000000..c138b4343474 --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py @@ -0,0 +1,6326 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +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.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1alpha.types import ( + evaluation_service, + search_service, +) +from google.cloud.discoveryengine_v1alpha.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import evaluation + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EvaluationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EvaluationServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EvaluationServiceClient._get_client_cert_source(None, False) is None + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + EvaluationServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + EvaluationServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + EvaluationServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + EvaluationServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, None) + == EvaluationServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, "grpc"), + (transports.EvaluationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_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", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_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_evaluation_service_client_get_transport_class(): + transport = EvaluationServiceClient.get_transport_class() + available_transports = [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceRestTransport, + ] + assert transport in available_transports + + transport = EvaluationServiceClient.get_transport_class("grpc") + assert transport == transports.EvaluationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_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(EvaluationServiceClient, "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(EvaluationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "true", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "false", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_evaluation_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + None, + ), + ], +) +def test_evaluation_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_evaluation_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.evaluation_service.transports.EvaluationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = EvaluationServiceClient( + 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", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_evaluation_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + response = client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +def test_get_evaluation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest() + + +def test_get_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + +def test_get_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + ) + response = await client.get_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest() + + +@pytest.mark.asyncio +async def test_get_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation + ] = mock_object + + request = {} + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + ) + response = await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +@pytest.mark.asyncio +async def test_get_evaluation_async_from_dict(): + await test_get_evaluation_async(request_type=dict) + + +def test_get_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = evaluation.Evaluation() + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation( + 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_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation( + 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_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluations), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest() + + +def test_list_evaluations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_evaluations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluations + ] = mock_rpc + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluations + ] = mock_object + + request = {} + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluations_async_from_dict(): + await test_list_evaluations_async(request_type=dict) + + +def test_list_evaluations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = evaluation_service.ListEvaluationsResponse() + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluations_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluations( + 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_evaluations_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluations( + 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_evaluations_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluations(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + +def test_list_evaluations_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluations(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_evaluations_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluations( + 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, evaluation.Evaluation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + 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_evaluations(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", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_evaluation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest() + + +def test_create_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateEvaluationRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest( + parent="parent_value", + ) + + +def test_create_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation + ] = mock_rpc + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest() + + +@pytest.mark.asyncio +async def test_create_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_evaluation + ] = mock_object + + request = {} + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__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_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_evaluation_async_from_dict(): + await test_create_evaluation_async(request_type=dict) + + +def test_create_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation( + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(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].evaluation + mock_val = gcd_evaluation.Evaluation(name="name_value") + assert arg == mock_val + + +def test_create_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation( + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(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].evaluation + mock_val = gcd_evaluation.Evaluation(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation_results), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest() + + +def test_list_evaluation_results_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationResultsRequest( + evaluation="evaluation_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_results(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest( + evaluation="evaluation_value", + page_token="page_token_value", + ) + + +def test_list_evaluation_results_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_results + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_results + ] = mock_object + + request = {} + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_from_dict(): + await test_list_evaluation_results_async(request_type=dict) + + +def test_list_evaluation_results_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.evaluation = "evaluation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationResultsResponse() + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation=evaluation_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_results_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.evaluation = "evaluation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation=evaluation_value", + ) in kw["metadata"] + + +def test_list_evaluation_results_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_results( + evaluation="evaluation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = "evaluation_value" + assert arg == mock_val + + +def test_list_evaluation_results_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_results( + evaluation="evaluation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = "evaluation_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +def test_list_evaluation_results_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("evaluation", ""),)), + ) + pager = client.list_evaluation_results(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in results + ) + + +def test_list_evaluation_results_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_results(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_evaluation_results_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_results( + 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, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + 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_evaluation_results(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", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/evaluations/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 = evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.Evaluation.pb(return_value) + 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_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +def test_get_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_rest_required_fields( + request_type=evaluation_service.GetEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation._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_evaluation._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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation.Evaluation.pb(return_value) + 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_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.GetEvaluationRequest.pb( + evaluation_service.GetEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation.Evaluation.to_json( + evaluation.Evaluation() + ) + + request = evaluation_service.GetEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.Evaluation() + + client.get_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_evaluation_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.GetEvaluationRequest +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/evaluations/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_evaluation(request) + + +def test_get_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/evaluations/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 = evaluation.Evaluation.pb(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_evaluation(**mock_args) + + # Establish that the underlying call 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/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +def test_get_evaluation_rest_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations_rest(request_type): + client = EvaluationServiceClient( + 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 = evaluation_service.ListEvaluationsResponse( + 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 = evaluation_service.ListEvaluationsResponse.pb(return_value) + 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_evaluations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluations + ] = mock_rpc + + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluations_rest_required_fields( + request_type=evaluation_service.ListEvaluationsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluations._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_evaluations._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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation_service.ListEvaluationsResponse.pb(return_value) + 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_evaluations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluations_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluations_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluations" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.ListEvaluationsRequest.pb( + evaluation_service.ListEvaluationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation_service.ListEvaluationsResponse.to_json( + evaluation_service.ListEvaluationsResponse() + ) + + request = evaluation_service.ListEvaluationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationsResponse() + + client.list_evaluations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluations_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.ListEvaluationsRequest +): + client = EvaluationServiceClient( + 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_evaluations(request) + + +def test_list_evaluations_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + + # 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 = evaluation_service.ListEvaluationsResponse.pb(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_evaluations(**mock_args) + + # Establish that the underlying call 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/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_list_evaluations_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + 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 = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationsResponse.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_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + pages = list(client.list_evaluations(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", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["evaluation"] = { + "name": "name_value", + "evaluation_spec": { + "search_request": { + "serving_config": "serving_config_value", + "branch": "branch_value", + "query": "query_value", + "image_query": {"image_bytes": "image_bytes_value"}, + "page_size": 951, + "page_token": "page_token_value", + "offset": 647, + "data_store_specs": [{"data_store": "data_store_value"}], + "filter": "filter_value", + "canonical_filter": "canonical_filter_value", + "order_by": "order_by_value", + "user_info": { + "user_id": "user_id_value", + "user_agent": "user_agent_value", + }, + "facet_specs": [ + { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + } + ], + "boost_spec": { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + }, + "params": {}, + "query_expansion_spec": { + "condition": 1, + "pin_unexpanded_results": True, + }, + "spell_correction_spec": {"mode": 1}, + "user_pseudo_id": "user_pseudo_id_value", + "content_search_spec": { + "snippet_spec": { + "max_snippet_count": 1840, + "reference_only": True, + "return_snippet": True, + }, + "summary_spec": { + "summary_result_count": 2196, + "include_citations": True, + "ignore_adversarial_query": True, + "ignore_non_summary_seeking_query": True, + "model_prompt_spec": {"preamble": "preamble_value"}, + "language_code": "language_code_value", + "model_spec": {"version": "version_value"}, + "use_semantic_chunks": True, + }, + "extractive_content_spec": { + "max_extractive_answer_count": 2907, + "max_extractive_segment_count": 3006, + "return_extractive_segment_score": True, + "num_previous_segments": 2289, + "num_next_segments": 1843, + }, + "search_result_mode": 1, + "chunk_spec": { + "num_previous_chunks": 2071, + "num_next_chunks": 1625, + }, + }, + "embedding_spec": { + "embedding_vectors": [ + {"field_path": "field_path_value", "vector": [0.66, 0.661]} + ] + }, + "ranking_expression": "ranking_expression_value", + "safe_search": True, + "user_labels": {}, + "custom_fine_tuning_spec": {"enable_search_adaptor": True}, + }, + "query_set_spec": {"sample_query_set": "sample_query_set_value"}, + }, + "quality_metrics": { + "doc_recall": { + "top_1": 0.483, + "top_3": 0.485, + "top_5": 0.487, + "top_10": 0.531, + }, + "doc_precision": {}, + "doc_ndcg": {}, + "page_recall": {}, + "page_ndcg": {}, + }, + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "create_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "error_samples": {}, + } + # 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 = evaluation_service.CreateEvaluationRequest.meta.fields["evaluation"] + + 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["evaluation"].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["evaluation"][field])): + del request_init["evaluation"][field][i][subfield] + else: + del request_init["evaluation"][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_evaluation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation + ] = mock_rpc + + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_evaluation_rest_required_fields( + request_type=evaluation_service.CreateEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation._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_evaluation._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 = EvaluationServiceClient( + 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_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "evaluation", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(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.EvaluationServiceRestInterceptor, "post_create_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_create_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.CreateEvaluationRequest.pb( + evaluation_service.CreateEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = evaluation_service.CreateEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_evaluation_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.CreateEvaluationRequest +): + client = EvaluationServiceClient( + 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_evaluation(request) + + +def test_create_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_evaluation(**mock_args) + + # Establish that the underlying call 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/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_create_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +def test_create_evaluation_rest_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation": "projects/sample1/locations/sample2/evaluations/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 = evaluation_service.ListEvaluationResultsResponse( + 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 = evaluation_service.ListEvaluationResultsResponse.pb(return_value) + 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_evaluation_results(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_results_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_results_rest_required_fields( + request_type=evaluation_service.ListEvaluationResultsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["evaluation"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["evaluation"] = "evaluation_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._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 "evaluation" in jsonified_request + assert jsonified_request["evaluation"] == "evaluation_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation_service.ListEvaluationResultsResponse.pb( + return_value + ) + 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_evaluation_results(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_results_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_results._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("evaluation",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_results_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_results" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_results" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.ListEvaluationResultsRequest.pb( + evaluation_service.ListEvaluationResultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + evaluation_service.ListEvaluationResultsResponse.to_json( + evaluation_service.ListEvaluationResultsResponse() + ) + ) + + request = evaluation_service.ListEvaluationResultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationResultsResponse() + + client.list_evaluation_results( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluation_results_rest_bad_request( + transport: str = "rest", + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation": "projects/sample1/locations/sample2/evaluations/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_evaluation_results(request) + + +def test_list_evaluation_results_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "evaluation": "projects/sample1/locations/sample2/evaluations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + evaluation="evaluation_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 = evaluation_service.ListEvaluationResultsResponse.pb(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_evaluation_results(**mock_args) + + # Establish that the underlying call 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/{evaluation=projects/*/locations/*/evaluations/*}:listResults" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_results_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +def test_list_evaluation_results_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + 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 = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationResultsResponse.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 = { + "evaluation": "projects/sample1/locations/sample2/evaluations/sample3" + } + + pager = client.list_evaluation_results(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in results + ) + + pages = list(client.list_evaluation_results(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.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EvaluationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +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 = EvaluationServiceClient.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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EvaluationServiceGrpcTransport, + ) + + +def test_evaluation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_evaluation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.evaluation_service.transports.EvaluationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_evaluation", + "list_evaluations", + "create_evaluation", + "list_evaluation_results", + "get_operation", + "cancel_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_evaluation_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.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport( + 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_evaluation_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.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport() + adc.assert_called_once() + + +def test_evaluation_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) + EvaluationServiceClient() + 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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, grpc_helpers), + (transports.EvaluationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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_evaluation_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.EvaluationServiceRestTransport( + 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_evaluation_service_rest_lro_client(): + client = EvaluationServiceClient( + 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_evaluation_service_host_no_port(transport_name): + client = EvaluationServiceClient( + 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_evaluation_service_host_with_port(transport_name): + client = EvaluationServiceClient( + 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_evaluation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EvaluationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EvaluationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 + session1 = client1.transport.create_evaluation._session + session2 = client2.transport.create_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_results._session + session2 = client2.transport.list_evaluation_results._session + assert session1 != session2 + + +def test_evaluation_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcTransport( + 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_evaluation_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + 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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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_evaluation_service_grpc_lro_client(): + client = EvaluationServiceClient( + 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_evaluation_service_grpc_lro_async_client(): + client = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient.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 = EvaluationServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_branch_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 = EvaluationServiceClient.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 = EvaluationServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_data_store_path(path) + assert expected == actual + + +def test_evaluation_path(): + project = "whelk" + location = "octopus" + evaluation = "oyster" + expected = ( + "projects/{project}/locations/{location}/evaluations/{evaluation}".format( + project=project, + location=location, + evaluation=evaluation, + ) + ) + actual = EvaluationServiceClient.evaluation_path(project, location, evaluation) + assert expected == actual + + +def test_parse_evaluation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "evaluation": "mussel", + } + path = EvaluationServiceClient.evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_path(path) + assert expected == actual + + +def test_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EvaluationServiceClient.location_path(project, location) + assert expected == actual + + +def test_parse_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = EvaluationServiceClient.location_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_location_path(path) + assert expected == actual + + +def test_sample_query_path(): + project = "squid" + location = "clam" + sample_query_set = "whelk" + sample_query = "octopus" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + actual = EvaluationServiceClient.sample_query_path( + project, location, sample_query_set, sample_query + ) + assert expected == actual + + +def test_parse_sample_query_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "sample_query_set": "cuttlefish", + "sample_query": "mussel", + } + path = EvaluationServiceClient.sample_query_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_sample_query_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "winkle" + location = "nautilus" + sample_query_set = "scallop" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = EvaluationServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "abalone", + "location": "squid", + "sample_query_set": "clam", + } + path = EvaluationServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_serving_config_path(): + project = "whelk" + location = "octopus" + data_store = "oyster" + serving_config = "nudibranch" + 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 = EvaluationServiceClient.serving_config_path( + project, location, data_store, serving_config + ) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "data_store": "winkle", + "serving_config": "nautilus", + } + path = EvaluationServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_serving_config_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = EvaluationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EvaluationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = EvaluationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EvaluationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = EvaluationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EvaluationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = EvaluationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EvaluationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EvaluationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EvaluationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.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.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = EvaluationServiceClient.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 = EvaluationServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = EvaluationServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = EvaluationServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceClient( + 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 = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceClient( + 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 = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient( + 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 = EvaluationServiceClient( + 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", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_service.py new file mode 100644 index 000000000000..d0e251470ab7 --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_service.py @@ -0,0 +1,7204 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +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.sample_query_service import ( + SampleQueryServiceAsyncClient, + SampleQueryServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import sample_query +from google.cloud.discoveryengine_v1alpha.types import sample_query_service + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SampleQueryServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + SampleQueryServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQueryServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SampleQueryServiceClient._get_client_cert_source(None, False) is None + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SampleQueryServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SampleQueryServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SampleQueryServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SampleQueryServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SampleQueryServiceClient._get_universe_domain(None, None) + == SampleQueryServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SampleQueryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SampleQueryServiceClient, "grpc"), + (SampleQueryServiceAsyncClient, "grpc_asyncio"), + (SampleQueryServiceClient, "rest"), + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, "grpc"), + (transports.SampleQueryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test_sample_query_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", + [ + (SampleQueryServiceClient, "grpc"), + (SampleQueryServiceAsyncClient, "grpc_asyncio"), + (SampleQueryServiceClient, "rest"), + ], +) +def test_sample_query_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_sample_query_service_client_get_transport_class(): + transport = SampleQueryServiceClient.get_transport_class() + available_transports = [ + transports.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceRestTransport, + ] + assert transport in available_transports + + transport = SampleQueryServiceClient.get_transport_class("grpc") + assert transport == transports.SampleQueryServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test_sample_query_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(SampleQueryServiceClient, "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(SampleQueryServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + "true", + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + "false", + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + "true", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sample_query_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQueryServiceClient, SampleQueryServiceAsyncClient] +) +@mock.patch.object( + SampleQueryServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQueryServiceAsyncClient), +) +def test_sample_query_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQueryServiceClient, SampleQueryServiceAsyncClient] +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test_sample_query_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test_sample_query_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + None, + ), + ], +) +def test_sample_query_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_sample_query_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.sample_query_service.transports.SampleQueryServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SampleQueryServiceClient( + 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", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sample_query_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + sample_query_service.GetSampleQueryRequest, + dict, + ], +) +def test_get_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery( + name="name_value", + ) + response = client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.GetSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_get_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest() + + +def test_get_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.GetSampleQueryRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest( + name="name_value", + ) + + +def test_get_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sample_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query + ] = mock_rpc + request = {} + client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.get_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_get_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_sample_query + ] = mock_object + + request = {} + await client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.GetSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.GetSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_sample_query_async_from_dict(): + await test_get_sample_query_async(request_type=dict) + + +def test_get_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.GetSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value = sample_query.SampleQuery() + client.get_sample_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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.GetSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery() + ) + await client.get_sample_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", + "name=name_value", + ) in kw["metadata"] + + +def test_get_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sample_query( + 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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sample_query( + 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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.ListSampleQueriesRequest, + dict, + ], +) +def test_list_sample_queries(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.ListSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_queries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceClient( + credentials=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_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest() + + +def test_list_sample_queries_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.ListSampleQueriesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_queries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_sample_queries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_queries in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_queries + ] = mock_rpc + request = {} + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_queries_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest() + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_sample_queries + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_sample_queries + ] = mock_object + + request = {} + await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_queries_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.ListSampleQueriesRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.ListSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_from_dict(): + await test_list_sample_queries_async(request_type=dict) + + +def test_list_sample_queries_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.ListSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value = sample_query_service.ListSampleQueriesResponse() + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.ListSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse() + ) + await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sample_queries( + 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_sample_queries_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sample_queries_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sample_queries( + 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_sample_queries_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +def test_list_sample_queries_pager(transport_name: str = "grpc"): + client = SampleQueryServiceClient( + 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_sample_queries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sample_queries(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query.SampleQuery) for i in results) + + +def test_list_sample_queries_pages(transport_name: str = "grpc"): + client = SampleQueryServiceClient( + 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_sample_queries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sample_queries(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_sample_queries_async_pager(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sample_queries( + 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, sample_query.SampleQuery) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_pages(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + 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_sample_queries(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", + [ + sample_query_service.CreateSampleQueryRequest, + dict, + ], +) +def test_create_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery( + name="name_value", + ) + response = client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.CreateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_create_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest() + + +def test_create_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.CreateSampleQueryRequest( + parent="parent_value", + sample_query_id="sample_query_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest( + parent="parent_value", + sample_query_id="sample_query_id_value", + ) + + +def test_create_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query + ] = mock_rpc + request = {} + client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.create_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_create_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_sample_query + ] = mock_object + + request = {} + await client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.CreateSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.CreateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_sample_query_async_from_dict(): + await test_create_sample_query_async(request_type=dict) + + +def test_create_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.CreateSampleQueryRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value = gcd_sample_query.SampleQuery() + client.create_sample_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", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.CreateSampleQueryRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + await client.create_sample_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", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sample_query( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ) + assert arg == mock_val + arg = args[0].sample_query_id + mock_val = "sample_query_id_value" + assert arg == mock_val + + +def test_create_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sample_query( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ) + assert arg == mock_val + arg = args[0].sample_query_id + mock_val = "sample_query_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.UpdateSampleQueryRequest, + dict, + ], +) +def test_update_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery( + name="name_value", + ) + response = client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.UpdateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_update_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +def test_update_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.UpdateSampleQueryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +def test_update_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query + ] = mock_rpc + request = {} + client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.update_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_update_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_sample_query + ] = mock_object + + request = {} + await client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.UpdateSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.UpdateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_sample_query_async_from_dict(): + await test_update_sample_query_async(request_type=dict) + + +def test_update_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.UpdateSampleQueryRequest() + + request.sample_query.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value = gcd_sample_query.SampleQuery() + client.update_sample_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", + "sample_query.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.UpdateSampleQueryRequest() + + request.sample_query.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + await client.update_sample_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", + "sample_query.name=name_value", + ) in kw["metadata"] + + +def test_update_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sample_query( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sample_query( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.DeleteSampleQueryRequest, + dict, + ], +) +def test_delete_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.DeleteSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest() + + +def test_delete_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.DeleteSampleQueryRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest( + name="name_value", + ) + + +def test_delete_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query + ] = mock_rpc + request = {} + client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_delete_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_sample_query + ] = mock_object + + request = {} + await client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.DeleteSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.DeleteSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_sample_query_async_from_dict(): + await test_delete_sample_query_async(request_type=dict) + + +def test_delete_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.DeleteSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value = None + client.delete_sample_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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.DeleteSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sample_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", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__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_sample_query( + 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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__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_sample_query( + 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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportSampleQueriesRequest, + dict, + ], +) +def test_import_sample_queries(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = import_config.ImportSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_sample_queries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceClient( + credentials=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_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest() + + +def test_import_sample_queries_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = import_config.ImportSampleQueriesRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_sample_queries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest( + parent="parent_value", + ) + + +def test_import_sample_queries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_sample_queries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_sample_queries + ] = mock_rpc + request = {} + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_sample_queries_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__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_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest() + + +@pytest.mark.asyncio +async def test_import_sample_queries_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_sample_queries + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.import_sample_queries + ] = mock_object + + request = {} + await client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_sample_queries_async( + transport: str = "grpc_asyncio", + request_type=import_config.ImportSampleQueriesRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__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_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = import_config.ImportSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_sample_queries_async_from_dict(): + await test_import_sample_queries_async(request_type=dict) + + +def test_import_sample_queries_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", + [ + sample_query_service.GetSampleQueryRequest, + dict, + ], +) +def test_get_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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 = sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_get_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sample_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query + ] = mock_rpc + + request = {} + client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_sample_query_rest_required_fields( + request_type=sample_query_service.GetSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_sample_query._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_sample_query._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_get_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_get_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.GetSampleQueryRequest.pb( + sample_query_service.GetSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = sample_query.SampleQuery.to_json( + sample_query.SampleQuery() + ) + + request = sample_query_service.GetSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query.SampleQuery() + + client.get_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.GetSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_get_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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 = sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_get_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +def test_get_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.ListSampleQueriesRequest, + dict, + ], +) +def test_list_sample_queries_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_service.ListSampleQueriesResponse( + 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 = sample_query_service.ListSampleQueriesResponse.pb(return_value) + 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_sample_queries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_queries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_queries in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_queries + ] = mock_rpc + + request = {} + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_sample_queries_rest_required_fields( + request_type=sample_query_service.ListSampleQueriesRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sample_queries._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_sample_queries._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_service.ListSampleQueriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_service.ListSampleQueriesResponse.pb( + return_value + ) + 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_sample_queries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sample_queries_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sample_queries._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sample_queries_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_list_sample_queries" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_list_sample_queries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.ListSampleQueriesRequest.pb( + sample_query_service.ListSampleQueriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + sample_query_service.ListSampleQueriesResponse.to_json( + sample_query_service.ListSampleQueriesResponse() + ) + ) + + request = sample_query_service.ListSampleQueriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_service.ListSampleQueriesResponse() + + client.list_sample_queries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sample_queries_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.ListSampleQueriesRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + +def test_list_sample_queries_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_service.ListSampleQueriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_service.ListSampleQueriesResponse.pb(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_sample_queries(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}/sampleQueries" + % client.transport._host, + args[1], + ) + + +def test_list_sample_queries_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +def test_list_sample_queries_rest_pager(transport: str = "rest"): + client = SampleQueryServiceClient( + 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 = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + sample_query_service.ListSampleQueriesResponse.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/sampleQuerySets/sample3" + } + + pager = client.list_sample_queries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query.SampleQuery) for i in results) + + pages = list(client.list_sample_queries(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", + [ + sample_query_service.CreateSampleQueryRequest, + dict, + ], +) +def test_create_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + request_init["sample_query"] = { + "query_entry": { + "query": "query_value", + "targets": [ + {"uri": "uri_value", "page_numbers": [1273, 1274], "score": 0.54} + ], + }, + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_service.CreateSampleQueryRequest.meta.fields[ + "sample_query" + ] + + 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["sample_query"].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["sample_query"][field])): + del request_init["sample_query"][field][i][subfield] + else: + del request_init["sample_query"][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_sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_create_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query + ] = mock_rpc + + request = {} + client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_sample_query_rest_required_fields( + request_type=sample_query_service.CreateSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sample_query_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "sampleQueryId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sampleQueryId" in jsonified_request + assert jsonified_request["sampleQueryId"] == request_init["sample_query_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sampleQueryId"] = "sample_query_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("sample_query_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 "sampleQueryId" in jsonified_request + assert jsonified_request["sampleQueryId"] == "sample_query_id_value" + + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [ + ( + "sampleQueryId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("sampleQueryId",)) + & set( + ( + "parent", + "sampleQuery", + "sampleQueryId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_create_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_create_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.CreateSampleQueryRequest.pb( + sample_query_service.CreateSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query.SampleQuery.to_json( + gcd_sample_query.SampleQuery() + ) + + request = sample_query_service.CreateSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query.SampleQuery() + + client.create_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.CreateSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query(request) + + +def test_create_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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_sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}/sampleQueries" + % client.transport._host, + args[1], + ) + + +def test_create_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +def test_create_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.UpdateSampleQueryRequest, + dict, + ], +) +def test_update_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4" + } + } + request_init["sample_query"] = { + "query_entry": { + "query": "query_value", + "targets": [ + {"uri": "uri_value", "page_numbers": [1273, 1274], "score": 0.54} + ], + }, + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4", + "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 = sample_query_service.UpdateSampleQueryRequest.meta.fields[ + "sample_query" + ] + + 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["sample_query"].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["sample_query"][field])): + del request_init["sample_query"][field][i][subfield] + else: + del request_init["sample_query"][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_sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_update_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query + ] = mock_rpc + + request = {} + client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_sample_query_rest_required_fields( + request_type=sample_query_service.UpdateSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_sample_query._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_sample_query._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("sampleQuery",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_update_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_update_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.UpdateSampleQueryRequest.pb( + sample_query_service.UpdateSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query.SampleQuery.to_json( + gcd_sample_query.SampleQuery() + ) + + request = sample_query_service.UpdateSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query.SampleQuery() + + client.update_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.UpdateSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_update_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/{sample_query.name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_update_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.DeleteSampleQueryRequest, + dict, + ], +) +def test_delete_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query + ] = mock_rpc + + request = {} + client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_sample_query_rest_required_fields( + request_type=sample_query_service.DeleteSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sample_query._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_sample_query._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 = SampleQueryServiceClient( + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_delete_sample_query" + ) as pre: + pre.assert_not_called() + pb_message = sample_query_service.DeleteSampleQueryRequest.pb( + sample_query_service.DeleteSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "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 = sample_query_service.DeleteSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.DeleteSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_delete_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/sampleQuerySets/sample3/sampleQueries/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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +def test_delete_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportSampleQueriesRequest, + dict, + ], +) +def test_import_sample_queries_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_sample_queries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_sample_queries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_sample_queries + ] = mock_rpc + + request = {} + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_sample_queries_rest_required_fields( + request_type=import_config.ImportSampleQueriesRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_sample_queries._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_sample_queries._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 = SampleQueryServiceClient( + 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_sample_queries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_sample_queries_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_sample_queries._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_sample_queries_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(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.SampleQueryServiceRestInterceptor, "post_import_sample_queries" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_import_sample_queries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportSampleQueriesRequest.pb( + import_config.ImportSampleQueriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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.ImportSampleQueriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_sample_queries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_sample_queries_rest_bad_request( + transport: str = "rest", request_type=import_config.ImportSampleQueriesRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + +def test_import_sample_queries_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SampleQueryServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SampleQueryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + transports.SampleQueryServiceRestTransport, + ], +) +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 = SampleQueryServiceClient.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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SampleQueryServiceGrpcTransport, + ) + + +def test_sample_query_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SampleQueryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sample_query_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.sample_query_service.transports.SampleQueryServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SampleQueryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_sample_query", + "list_sample_queries", + "create_sample_query", + "update_sample_query", + "delete_sample_query", + "import_sample_queries", + "get_operation", + "cancel_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_sample_query_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.sample_query_service.transports.SampleQueryServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQueryServiceTransport( + 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_sample_query_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.sample_query_service.transports.SampleQueryServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQueryServiceTransport() + adc.assert_called_once() + + +def test_sample_query_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) + SampleQueryServiceClient() + 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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + transports.SampleQueryServiceRestTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, grpc_helpers), + (transports.SampleQueryServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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_sample_query_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.SampleQueryServiceRestTransport( + 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_sample_query_service_rest_lro_client(): + client = SampleQueryServiceClient( + 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_sample_query_service_host_no_port(transport_name): + client = SampleQueryServiceClient( + 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_sample_query_service_host_with_port(transport_name): + client = SampleQueryServiceClient( + 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_sample_query_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SampleQueryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SampleQueryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_sample_query._session + session2 = client2.transport.get_sample_query._session + assert session1 != session2 + session1 = client1.transport.list_sample_queries._session + session2 = client2.transport.list_sample_queries._session + assert session1 != session2 + session1 = client1.transport.create_sample_query._session + session2 = client2.transport.create_sample_query._session + assert session1 != session2 + session1 = client1.transport.update_sample_query._session + session2 = client2.transport.update_sample_query._session + assert session1 != session2 + session1 = client1.transport.delete_sample_query._session + session2 = client2.transport.delete_sample_query._session + assert session1 != session2 + session1 = client1.transport.import_sample_queries._session + session2 = client2.transport.import_sample_queries._session + assert session1 != session2 + + +def test_sample_query_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQueryServiceGrpcTransport( + 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_sample_query_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQueryServiceGrpcAsyncIOTransport( + 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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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_sample_query_service_grpc_lro_client(): + client = SampleQueryServiceClient( + 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_sample_query_service_grpc_lro_async_client(): + client = SampleQueryServiceAsyncClient( + 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_sample_query_path(): + project = "squid" + location = "clam" + sample_query_set = "whelk" + sample_query = "octopus" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + actual = SampleQueryServiceClient.sample_query_path( + project, location, sample_query_set, sample_query + ) + assert expected == actual + + +def test_parse_sample_query_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "sample_query_set": "cuttlefish", + "sample_query": "mussel", + } + path = SampleQueryServiceClient.sample_query_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_sample_query_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "winkle" + location = "nautilus" + sample_query_set = "scallop" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = SampleQueryServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "abalone", + "location": "squid", + "sample_query_set": "clam", + } + path = SampleQueryServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SampleQueryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SampleQueryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SampleQueryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SampleQueryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SampleQueryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SampleQueryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = SampleQueryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SampleQueryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.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 = SampleQueryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SampleQueryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.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.SampleQueryServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SampleQueryServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SampleQueryServiceClient.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 = SampleQueryServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SampleQueryServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SampleQueryServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceAsyncClient( + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceAsyncClient( + 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceClient( + 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", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_set_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_set_service.py new file mode 100644 index 000000000000..5a46c095dc4b --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_sample_query_set_service.py @@ -0,0 +1,6631 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +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.sample_query_set_service import ( + SampleQuerySetServiceAsyncClient, + SampleQuerySetServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1alpha.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1alpha.types import sample_query_set +from google.cloud.discoveryengine_v1alpha.types import sample_query_set_service + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SampleQuerySetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + SampleQuerySetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQuerySetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SampleQuerySetServiceClient._get_client_cert_source(None, False) is None + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SampleQuerySetServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SampleQuerySetServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SampleQuerySetServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SampleQuerySetServiceClient._get_universe_domain(None, None) + == SampleQuerySetServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SampleQuerySetServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SampleQuerySetServiceClient, "grpc"), + (SampleQuerySetServiceAsyncClient, "grpc_asyncio"), + (SampleQuerySetServiceClient, "rest"), + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, "grpc"), + (transports.SampleQuerySetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SampleQuerySetServiceRestTransport, "rest"), + ], +) +def test_sample_query_set_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", + [ + (SampleQuerySetServiceClient, "grpc"), + (SampleQuerySetServiceAsyncClient, "grpc_asyncio"), + (SampleQuerySetServiceClient, "rest"), + ], +) +def test_sample_query_set_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_sample_query_set_service_client_get_transport_class(): + transport = SampleQuerySetServiceClient.get_transport_class() + available_transports = [ + transports.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceRestTransport, + ] + assert transport in available_transports + + transport = SampleQuerySetServiceClient.get_transport_class("grpc") + assert transport == transports.SampleQuerySetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_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(SampleQuerySetServiceClient, "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(SampleQuerySetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + "true", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + "false", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + "true", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sample_query_set_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQuerySetServiceClient, SampleQuerySetServiceAsyncClient] +) +@mock.patch.object( + SampleQuerySetServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQuerySetServiceClient, SampleQuerySetServiceAsyncClient] +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +def test_sample_query_set_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + None, + ), + ], +) +def test_sample_query_set_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_sample_query_set_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.transports.SampleQuerySetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SampleQuerySetServiceClient( + 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", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sample_query_set_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + sample_query_set_service.GetSampleQuerySetRequest, + dict, + ], +) +def test_get_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.GetSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest() + + +def test_get_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.GetSampleQuerySetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest( + name="name_value", + ) + + +def test_get_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_sample_query_set in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query_set + ] = mock_rpc + request = {} + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_sample_query_set + ] = mock_object + + request = {} + await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.GetSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async_from_dict(): + await test_get_sample_query_set_async(request_type=dict) + + +def test_get_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.GetSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value = sample_query_set.SampleQuerySet() + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.GetSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet() + ) + await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sample_query_set( + 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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sample_query_set( + 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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.ListSampleQuerySetsRequest, + dict, + ], +) +def test_list_sample_query_sets(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.ListSampleQuerySetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_query_sets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_sets), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_query_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest() + + +def test_list_sample_query_sets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.ListSampleQuerySetsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_query_sets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_sample_query_sets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_query_sets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_query_sets + ] = mock_rpc + request = {} + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_query_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest() + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_sample_query_sets + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_sample_query_sets + ] = mock_object + + request = {} + await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.ListSampleQuerySetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_from_dict(): + await test_list_sample_query_sets_async(request_type=dict) + + +def test_list_sample_query_sets_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.ListSampleQuerySetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_sets_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.ListSampleQuerySetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_sets_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sample_query_sets( + 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_sample_query_sets_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sample_query_sets( + 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_sample_query_sets_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +def test_list_sample_query_sets_pager(transport_name: str = "grpc"): + client = SampleQuerySetServiceClient( + 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_sample_query_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sample_query_sets(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query_set.SampleQuerySet) for i in results) + + +def test_list_sample_query_sets_pages(transport_name: str = "grpc"): + client = SampleQuerySetServiceClient( + 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_sample_query_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sample_query_sets(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_sample_query_sets_async_pager(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sample_query_sets( + 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, sample_query_set.SampleQuerySet) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_pages(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + 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_sample_query_sets(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", + [ + sample_query_set_service.CreateSampleQuerySetRequest, + dict, + ], +) +def test_create_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.CreateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest() + + +def test_create_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set_id="sample_query_set_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set_id="sample_query_set_id_value", + ) + + +def test_create_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query_set + ] = mock_rpc + request = {} + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_sample_query_set + ] = mock_object + + request = {} + await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.CreateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async_from_dict(): + await test_create_sample_query_set_async(request_type=dict) + + +def test_create_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.CreateSampleQuerySetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value = gcd_sample_query_set.SampleQuerySet() + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.CreateSampleQuerySetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sample_query_set( + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(name="name_value") + assert arg == mock_val + arg = args[0].sample_query_set_id + mock_val = "sample_query_set_id_value" + assert arg == mock_val + + +def test_create_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sample_query_set( + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(name="name_value") + assert arg == mock_val + arg = args[0].sample_query_set_id + mock_val = "sample_query_set_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.UpdateSampleQuerySetRequest, + dict, + ], +) +def test_update_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.UpdateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +def test_update_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +def test_update_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query_set + ] = mock_rpc + request = {} + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_sample_query_set + ] = mock_object + + request = {} + await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.UpdateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async_from_dict(): + await test_update_sample_query_set_async(request_type=dict) + + +def test_update_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + request.sample_query_set.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value = gcd_sample_query_set.SampleQuerySet() + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "sample_query_set.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + request.sample_query_set.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "sample_query_set.name=name_value", + ) in kw["metadata"] + + +def test_update_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sample_query_set( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sample_query_set( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.DeleteSampleQuerySetRequest, + dict, + ], +) +def test_delete_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.DeleteSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest() + + +def test_delete_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest( + name="name_value", + ) + + +def test_delete_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query_set + ] = mock_rpc + request = {} + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_sample_query_set + ] = mock_object + + request = {} + await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.DeleteSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async_from_dict(): + await test_delete_sample_query_set_async(request_type=dict) + + +def test_delete_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.DeleteSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value = None + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.DeleteSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__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_sample_query_set( + 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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__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_sample_query_set( + 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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.GetSampleQuerySetRequest, + dict, + ], +) +def test_get_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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 = sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_sample_query_set in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query_set + ] = mock_rpc + + request = {} + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_get_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_get_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.GetSampleQuerySetRequest.pb( + sample_query_set_service.GetSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = sample_query_set.SampleQuerySet.to_json( + sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.GetSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_set.SampleQuerySet() + + client.get_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_get_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_set.SampleQuerySet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_get_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +def test_get_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.ListSampleQuerySetsRequest, + dict, + ], +) +def test_list_sample_query_sets_rest(request_type): + client = SampleQuerySetServiceClient( + 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 = sample_query_set_service.ListSampleQuerySetsResponse( + 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + return_value + ) + 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_sample_query_sets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_query_sets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_query_sets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_query_sets + ] = mock_rpc + + request = {} + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_sample_query_sets_rest_required_fields( + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sample_query_sets._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_sample_query_sets._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_set_service.ListSampleQuerySetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + return_value + ) + 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_sample_query_sets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sample_query_sets_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sample_query_sets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sample_query_sets_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_list_sample_query_sets" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_list_sample_query_sets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.ListSampleQuerySetsRequest.pb( + sample_query_set_service.ListSampleQuerySetsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + sample_query_set_service.ListSampleQuerySetsResponse.to_json( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + ) + + request = sample_query_set_service.ListSampleQuerySetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + client.list_sample_query_sets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sample_query_sets_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + client = SampleQuerySetServiceClient( + 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_sample_query_sets(request) + + +def test_list_sample_query_sets_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + # 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + 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_sample_query_sets(**mock_args) + + # Establish that the underlying call 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/*}/sampleQuerySets" + % client.transport._host, + args[1], + ) + + +def test_list_sample_query_sets_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +def test_list_sample_query_sets_rest_pager(transport: str = "rest"): + client = SampleQuerySetServiceClient( + 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 = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + sample_query_set_service.ListSampleQuerySetsResponse.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_sample_query_sets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query_set.SampleQuerySet) for i in results) + + pages = list(client.list_sample_query_sets(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", + [ + sample_query_set_service.CreateSampleQuerySetRequest, + dict, + ], +) +def test_create_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["sample_query_set"] = { + "name": "name_value", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_set_service.CreateSampleQuerySetRequest.meta.fields[ + "sample_query_set" + ] + + 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["sample_query_set"].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["sample_query_set"][field])): + del request_init["sample_query_set"][field][i][subfield] + else: + del request_init["sample_query_set"][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_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query_set + ] = mock_rpc + + request = {} + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sample_query_set_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "sampleQuerySetId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sampleQuerySetId" in jsonified_request + assert jsonified_request["sampleQuerySetId"] == request_init["sample_query_set_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sampleQuerySetId"] = "sample_query_set_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("sample_query_set_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 "sampleQuerySetId" in jsonified_request + assert jsonified_request["sampleQuerySetId"] == "sample_query_set_id_value" + + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [ + ( + "sampleQuerySetId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("sampleQuerySetId",)) + & set( + ( + "parent", + "sampleQuerySet", + "sampleQuerySetId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_create_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_create_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.CreateSampleQuerySetRequest.pb( + sample_query_set_service.CreateSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query_set.SampleQuerySet.to_json( + gcd_sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.CreateSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query_set.SampleQuerySet() + + client.create_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + 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_sample_query_set(request) + + +def test_create_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query_set.SampleQuerySet() + + # 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", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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_sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*}/sampleQuerySets" + % client.transport._host, + args[1], + ) + + +def test_create_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +def test_create_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.UpdateSampleQuerySetRequest, + dict, + ], +) +def test_update_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + } + request_init["sample_query_set"] = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_set_service.UpdateSampleQuerySetRequest.meta.fields[ + "sample_query_set" + ] + + 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["sample_query_set"].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["sample_query_set"][field])): + del request_init["sample_query_set"][field][i][subfield] + else: + del request_init["sample_query_set"][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_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query_set + ] = mock_rpc + + request = {} + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("sampleQuerySet",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_update_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_update_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.UpdateSampleQuerySetRequest.pb( + sample_query_set_service.UpdateSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query_set.SampleQuerySet.to_json( + gcd_sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.UpdateSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query_set.SampleQuerySet() + + client.update_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_update_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query_set.SampleQuerySet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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_sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/{sample_query_set.name=projects/*/locations/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.DeleteSampleQuerySetRequest, + dict, + ], +) +def test_delete_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query_set + ] = mock_rpc + + request = {} + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_delete_sample_query_set" + ) as pre: + pre.assert_not_called() + pb_message = sample_query_set_service.DeleteSampleQuerySetRequest.pb( + sample_query_set_service.DeleteSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "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 = sample_query_set_service.DeleteSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_delete_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/sampleQuerySets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +def test_delete_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SampleQuerySetServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SampleQuerySetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + transports.SampleQuerySetServiceRestTransport, + ], +) +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 = SampleQuerySetServiceClient.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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SampleQuerySetServiceGrpcTransport, + ) + + +def test_sample_query_set_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SampleQuerySetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sample_query_set_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.sample_query_set_service.transports.SampleQuerySetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SampleQuerySetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_sample_query_set", + "list_sample_query_sets", + "create_sample_query_set", + "update_sample_query_set", + "delete_sample_query_set", + "get_operation", + "cancel_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_sample_query_set_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.sample_query_set_service.transports.SampleQuerySetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQuerySetServiceTransport( + 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_sample_query_set_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.sample_query_set_service.transports.SampleQuerySetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQuerySetServiceTransport() + adc.assert_called_once() + + +def test_sample_query_set_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) + SampleQuerySetServiceClient() + 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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + transports.SampleQuerySetServiceRestTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, grpc_helpers), + (transports.SampleQuerySetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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_sample_query_set_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.SampleQuerySetServiceRestTransport( + 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_sample_query_set_service_host_no_port(transport_name): + client = SampleQuerySetServiceClient( + 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_sample_query_set_service_host_with_port(transport_name): + client = SampleQuerySetServiceClient( + 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_sample_query_set_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SampleQuerySetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SampleQuerySetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_sample_query_set._session + session2 = client2.transport.get_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.list_sample_query_sets._session + session2 = client2.transport.list_sample_query_sets._session + assert session1 != session2 + session1 = client1.transport.create_sample_query_set._session + session2 = client2.transport.create_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.update_sample_query_set._session + session2 = client2.transport.update_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.delete_sample_query_set._session + session2 = client2.transport.delete_sample_query_set._session + assert session1 != session2 + + +def test_sample_query_set_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQuerySetServiceGrpcTransport( + 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_sample_query_set_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQuerySetServiceGrpcAsyncIOTransport( + 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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SampleQuerySetServiceClient.location_path(project, location) + assert expected == actual + + +def test_parse_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SampleQuerySetServiceClient.location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_location_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "oyster" + location = "nudibranch" + sample_query_set = "cuttlefish" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = SampleQuerySetServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "mussel", + "location": "winkle", + "sample_query_set": "nautilus", + } + path = SampleQuerySetServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SampleQuerySetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = SampleQuerySetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SampleQuerySetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = SampleQuerySetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SampleQuerySetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = SampleQuerySetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = SampleQuerySetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = SampleQuerySetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SampleQuerySetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = SampleQuerySetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.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.SampleQuerySetServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SampleQuerySetServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SampleQuerySetServiceClient.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 = SampleQuerySetServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SampleQuerySetServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SampleQuerySetServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceAsyncClient( + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceAsyncClient( + 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceClient( + 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", + [ + (SampleQuerySetServiceClient, transports.SampleQuerySetServiceGrpcTransport), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py index 227deb21bf1a..290a1124851d 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py @@ -3351,6 +3351,12 @@ def test_create_data_store_rest(request_type): "create_time": {"seconds": 751, "nanos": 543}, "document_processing_config": { "name": "name_value", + "chunking_config": { + "layout_based_chunking_config": { + "chunk_size": 1075, + "include_ancestor_headings": True, + } + }, "default_parsing_config": { "digital_parsing_config": {}, "ocr_parsing_config": { @@ -3360,6 +3366,7 @@ def test_create_data_store_rest(request_type): ], "use_native_text": True, }, + "layout_parsing_config": {}, }, "parsing_config_overrides": {}, }, @@ -4783,6 +4790,12 @@ def test_update_data_store_rest(request_type): "create_time": {"seconds": 751, "nanos": 543}, "document_processing_config": { "name": "name_value", + "chunking_config": { + "layout_based_chunking_config": { + "chunk_size": 1075, + "include_ancestor_headings": True, + } + }, "default_parsing_config": { "digital_parsing_config": {}, "ocr_parsing_config": { @@ -4792,6 +4805,7 @@ def test_update_data_store_rest(request_type): ], "use_native_text": True, }, + "layout_parsing_config": {}, }, "parsing_config_overrides": {}, }, diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py new file mode 100644 index 000000000000..0112d3ef8f2b --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py @@ -0,0 +1,6322 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +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_v1beta.services.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1beta.types import evaluation_service, search_service +from google.cloud.discoveryengine_v1beta.types import evaluation as gcd_evaluation +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import evaluation + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EvaluationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EvaluationServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EvaluationServiceClient._get_client_cert_source(None, False) is None + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + EvaluationServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + EvaluationServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + EvaluationServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + EvaluationServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, None) + == EvaluationServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, "grpc"), + (transports.EvaluationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_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", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_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_evaluation_service_client_get_transport_class(): + transport = EvaluationServiceClient.get_transport_class() + available_transports = [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceRestTransport, + ] + assert transport in available_transports + + transport = EvaluationServiceClient.get_transport_class("grpc") + assert transport == transports.EvaluationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_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(EvaluationServiceClient, "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(EvaluationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "true", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "false", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_evaluation_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + None, + ), + ], +) +def test_evaluation_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_evaluation_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.evaluation_service.transports.EvaluationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = EvaluationServiceClient( + 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", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_evaluation_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + response = client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +def test_get_evaluation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest() + + +def test_get_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + +def test_get_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + ) + response = await client.get_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest() + + +@pytest.mark.asyncio +async def test_get_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation + ] = mock_object + + request = {} + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + ) + response = await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +@pytest.mark.asyncio +async def test_get_evaluation_async_from_dict(): + await test_get_evaluation_async(request_type=dict) + + +def test_get_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = evaluation.Evaluation() + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation( + 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_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation( + 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_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluations), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest() + + +def test_list_evaluations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_evaluations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluations + ] = mock_rpc + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluations + ] = mock_object + + request = {} + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluations_async_from_dict(): + await test_list_evaluations_async(request_type=dict) + + +def test_list_evaluations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = evaluation_service.ListEvaluationsResponse() + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluations_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluations( + 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_evaluations_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluations( + 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_evaluations_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluations(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + +def test_list_evaluations_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluations(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_evaluations_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluations( + 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, evaluation.Evaluation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + 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_evaluations(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", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_evaluation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest() + + +def test_create_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateEvaluationRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest( + parent="parent_value", + ) + + +def test_create_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation + ] = mock_rpc + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest() + + +@pytest.mark.asyncio +async def test_create_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_evaluation + ] = mock_object + + request = {} + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation), "__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_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_evaluation_async_from_dict(): + await test_create_evaluation_async(request_type=dict) + + +def test_create_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation( + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(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].evaluation + mock_val = gcd_evaluation.Evaluation(name="name_value") + assert arg == mock_val + + +def test_create_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__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_evaluation( + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(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].evaluation + mock_val = gcd_evaluation.Evaluation(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceClient( + credentials=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_evaluation_results), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest() + + +def test_list_evaluation_results_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationResultsRequest( + evaluation="evaluation_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_results(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest( + evaluation="evaluation_value", + page_token="page_token_value", + ) + + +def test_list_evaluation_results_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_results + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_results + ] = mock_object + + request = {} + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_from_dict(): + await test_list_evaluation_results_async(request_type=dict) + + +def test_list_evaluation_results_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.evaluation = "evaluation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationResultsResponse() + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation=evaluation_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_results_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.evaluation = "evaluation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation=evaluation_value", + ) in kw["metadata"] + + +def test_list_evaluation_results_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_results( + evaluation="evaluation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = "evaluation_value" + assert arg == mock_val + + +def test_list_evaluation_results_flattened_error(): + client = EvaluationServiceClient( + credentials=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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_results( + evaluation="evaluation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = "evaluation_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +def test_list_evaluation_results_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("evaluation", ""),)), + ) + pager = client.list_evaluation_results(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in results + ) + + +def test_list_evaluation_results_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + 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_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_results(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_evaluation_results_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_results( + 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, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + 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_evaluation_results(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", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/evaluations/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 = evaluation.Evaluation( + name="name_value", + state=evaluation.Evaluation.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.Evaluation.pb(return_value) + 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_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.state == evaluation.Evaluation.State.PENDING + + +def test_get_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_rest_required_fields( + request_type=evaluation_service.GetEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation._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_evaluation._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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation.Evaluation.pb(return_value) + 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_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.GetEvaluationRequest.pb( + evaluation_service.GetEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation.Evaluation.to_json( + evaluation.Evaluation() + ) + + request = evaluation_service.GetEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.Evaluation() + + client.get_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_evaluation_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.GetEvaluationRequest +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/evaluations/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_evaluation(request) + + +def test_get_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/evaluations/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 = evaluation.Evaluation.pb(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_evaluation(**mock_args) + + # Establish that the underlying call 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/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +def test_get_evaluation_rest_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations_rest(request_type): + client = EvaluationServiceClient( + 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 = evaluation_service.ListEvaluationsResponse( + 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 = evaluation_service.ListEvaluationsResponse.pb(return_value) + 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_evaluations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluations + ] = mock_rpc + + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluations_rest_required_fields( + request_type=evaluation_service.ListEvaluationsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluations._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_evaluations._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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation_service.ListEvaluationsResponse.pb(return_value) + 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_evaluations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluations_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluations_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluations" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.ListEvaluationsRequest.pb( + evaluation_service.ListEvaluationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = evaluation_service.ListEvaluationsResponse.to_json( + evaluation_service.ListEvaluationsResponse() + ) + + request = evaluation_service.ListEvaluationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationsResponse() + + client.list_evaluations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluations_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.ListEvaluationsRequest +): + client = EvaluationServiceClient( + 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_evaluations(request) + + +def test_list_evaluations_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + + # 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 = evaluation_service.ListEvaluationsResponse.pb(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_evaluations(**mock_args) + + # Establish that the underlying call 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/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_list_evaluations_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + 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 = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationsResponse.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_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + pages = list(client.list_evaluations(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", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["evaluation"] = { + "name": "name_value", + "evaluation_spec": { + "search_request": { + "serving_config": "serving_config_value", + "branch": "branch_value", + "query": "query_value", + "image_query": {"image_bytes": "image_bytes_value"}, + "page_size": 951, + "page_token": "page_token_value", + "offset": 647, + "data_store_specs": [{"data_store": "data_store_value"}], + "filter": "filter_value", + "canonical_filter": "canonical_filter_value", + "order_by": "order_by_value", + "user_info": { + "user_id": "user_id_value", + "user_agent": "user_agent_value", + }, + "facet_specs": [ + { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + } + ], + "boost_spec": { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + }, + "params": {}, + "query_expansion_spec": { + "condition": 1, + "pin_unexpanded_results": True, + }, + "spell_correction_spec": {"mode": 1}, + "user_pseudo_id": "user_pseudo_id_value", + "content_search_spec": { + "snippet_spec": { + "max_snippet_count": 1840, + "reference_only": True, + "return_snippet": True, + }, + "summary_spec": { + "summary_result_count": 2196, + "include_citations": True, + "ignore_adversarial_query": True, + "ignore_non_summary_seeking_query": True, + "model_prompt_spec": {"preamble": "preamble_value"}, + "language_code": "language_code_value", + "model_spec": {"version": "version_value"}, + "use_semantic_chunks": True, + }, + "extractive_content_spec": { + "max_extractive_answer_count": 2907, + "max_extractive_segment_count": 3006, + "return_extractive_segment_score": True, + "num_previous_segments": 2289, + "num_next_segments": 1843, + }, + "search_result_mode": 1, + "chunk_spec": { + "num_previous_chunks": 2071, + "num_next_chunks": 1625, + }, + }, + "embedding_spec": { + "embedding_vectors": [ + {"field_path": "field_path_value", "vector": [0.66, 0.661]} + ] + }, + "ranking_expression": "ranking_expression_value", + "safe_search": True, + "user_labels": {}, + }, + "query_set_spec": {"sample_query_set": "sample_query_set_value"}, + }, + "quality_metrics": { + "doc_recall": { + "top_1": 0.483, + "top_3": 0.485, + "top_5": 0.487, + "top_10": 0.531, + }, + "doc_precision": {}, + "doc_ndcg": {}, + "page_recall": {}, + "page_ndcg": {}, + }, + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "create_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "error_samples": {}, + } + # 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 = evaluation_service.CreateEvaluationRequest.meta.fields["evaluation"] + + 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["evaluation"].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["evaluation"][field])): + del request_init["evaluation"][field][i][subfield] + else: + del request_init["evaluation"][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_evaluation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation + ] = mock_rpc + + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_evaluation_rest_required_fields( + request_type=evaluation_service.CreateEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation._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_evaluation._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 = EvaluationServiceClient( + 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_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "evaluation", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(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.EvaluationServiceRestInterceptor, "post_create_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_create_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.CreateEvaluationRequest.pb( + evaluation_service.CreateEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = evaluation_service.CreateEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_evaluation_rest_bad_request( + transport: str = "rest", request_type=evaluation_service.CreateEvaluationRequest +): + client = EvaluationServiceClient( + 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_evaluation(request) + + +def test_create_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_evaluation(**mock_args) + + # Establish that the underlying call 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/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_create_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcd_evaluation.Evaluation(name="name_value"), + ) + + +def test_create_evaluation_rest_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation": "projects/sample1/locations/sample2/evaluations/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 = evaluation_service.ListEvaluationResultsResponse( + 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 = evaluation_service.ListEvaluationResultsResponse.pb(return_value) + 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_evaluation_results(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_results_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_results_rest_required_fields( + request_type=evaluation_service.ListEvaluationResultsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["evaluation"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["evaluation"] = "evaluation_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._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 "evaluation" in jsonified_request + assert jsonified_request["evaluation"] == "evaluation_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = evaluation_service.ListEvaluationResultsResponse.pb( + return_value + ) + 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_evaluation_results(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_results_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_results._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("evaluation",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_results_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_results" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_results" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = evaluation_service.ListEvaluationResultsRequest.pb( + evaluation_service.ListEvaluationResultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + evaluation_service.ListEvaluationResultsResponse.to_json( + evaluation_service.ListEvaluationResultsResponse() + ) + ) + + request = evaluation_service.ListEvaluationResultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationResultsResponse() + + client.list_evaluation_results( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_evaluation_results_rest_bad_request( + transport: str = "rest", + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation": "projects/sample1/locations/sample2/evaluations/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_evaluation_results(request) + + +def test_list_evaluation_results_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "evaluation": "projects/sample1/locations/sample2/evaluations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + evaluation="evaluation_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 = evaluation_service.ListEvaluationResultsResponse.pb(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_evaluation_results(**mock_args) + + # Establish that the underlying call 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/{evaluation=projects/*/locations/*/evaluations/*}:listResults" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_results_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.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_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + evaluation="evaluation_value", + ) + + +def test_list_evaluation_results_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + 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 = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + evaluation_service.ListEvaluationResultsResponse.EvaluationResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationResultsResponse.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 = { + "evaluation": "projects/sample1/locations/sample2/evaluations/sample3" + } + + pager = client.list_evaluation_results(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, evaluation_service.ListEvaluationResultsResponse.EvaluationResult + ) + for i in results + ) + + pages = list(client.list_evaluation_results(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.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EvaluationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +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 = EvaluationServiceClient.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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EvaluationServiceGrpcTransport, + ) + + +def test_evaluation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_evaluation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.evaluation_service.transports.EvaluationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_evaluation", + "list_evaluations", + "create_evaluation", + "list_evaluation_results", + "get_operation", + "cancel_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_evaluation_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.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport( + 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_evaluation_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.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport() + adc.assert_called_once() + + +def test_evaluation_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) + EvaluationServiceClient() + 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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, grpc_helpers), + (transports.EvaluationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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_evaluation_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.EvaluationServiceRestTransport( + 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_evaluation_service_rest_lro_client(): + client = EvaluationServiceClient( + 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_evaluation_service_host_no_port(transport_name): + client = EvaluationServiceClient( + 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_evaluation_service_host_with_port(transport_name): + client = EvaluationServiceClient( + 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_evaluation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EvaluationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EvaluationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 + session1 = client1.transport.create_evaluation._session + session2 = client2.transport.create_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_results._session + session2 = client2.transport.list_evaluation_results._session + assert session1 != session2 + + +def test_evaluation_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcTransport( + 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_evaluation_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + 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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_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_evaluation_service_grpc_lro_client(): + client = EvaluationServiceClient( + 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_evaluation_service_grpc_lro_async_client(): + client = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient.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 = EvaluationServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_branch_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 = EvaluationServiceClient.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 = EvaluationServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_data_store_path(path) + assert expected == actual + + +def test_evaluation_path(): + project = "whelk" + location = "octopus" + evaluation = "oyster" + expected = ( + "projects/{project}/locations/{location}/evaluations/{evaluation}".format( + project=project, + location=location, + evaluation=evaluation, + ) + ) + actual = EvaluationServiceClient.evaluation_path(project, location, evaluation) + assert expected == actual + + +def test_parse_evaluation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "evaluation": "mussel", + } + path = EvaluationServiceClient.evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_path(path) + assert expected == actual + + +def test_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EvaluationServiceClient.location_path(project, location) + assert expected == actual + + +def test_parse_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = EvaluationServiceClient.location_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_location_path(path) + assert expected == actual + + +def test_sample_query_path(): + project = "squid" + location = "clam" + sample_query_set = "whelk" + sample_query = "octopus" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + actual = EvaluationServiceClient.sample_query_path( + project, location, sample_query_set, sample_query + ) + assert expected == actual + + +def test_parse_sample_query_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "sample_query_set": "cuttlefish", + "sample_query": "mussel", + } + path = EvaluationServiceClient.sample_query_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_sample_query_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "winkle" + location = "nautilus" + sample_query_set = "scallop" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = EvaluationServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "abalone", + "location": "squid", + "sample_query_set": "clam", + } + path = EvaluationServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_serving_config_path(): + project = "whelk" + location = "octopus" + data_store = "oyster" + serving_config = "nudibranch" + 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 = EvaluationServiceClient.serving_config_path( + project, location, data_store, serving_config + ) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "data_store": "winkle", + "serving_config": "nautilus", + } + path = EvaluationServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_serving_config_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = EvaluationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EvaluationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = EvaluationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EvaluationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = EvaluationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EvaluationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = EvaluationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EvaluationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EvaluationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EvaluationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.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.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = EvaluationServiceClient.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 = EvaluationServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = EvaluationServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = EvaluationServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceClient( + 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 = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EvaluationServiceClient( + 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 = EvaluationServiceAsyncClient( + 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 = EvaluationServiceClient( + 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 = EvaluationServiceClient( + 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", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_service.py new file mode 100644 index 000000000000..94306274042d --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_service.py @@ -0,0 +1,7204 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +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_v1beta.services.sample_query_service import ( + SampleQueryServiceAsyncClient, + SampleQueryServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1beta.types import sample_query as gcd_sample_query +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import sample_query +from google.cloud.discoveryengine_v1beta.types import sample_query_service + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SampleQueryServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQueryServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + SampleQueryServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQueryServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SampleQueryServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SampleQueryServiceClient._get_client_cert_source(None, False) is None + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SampleQueryServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SampleQueryServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SampleQueryServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SampleQueryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQueryServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SampleQueryServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQueryServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SampleQueryServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SampleQueryServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SampleQueryServiceClient._get_universe_domain(None, None) + == SampleQueryServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SampleQueryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SampleQueryServiceClient, "grpc"), + (SampleQueryServiceAsyncClient, "grpc_asyncio"), + (SampleQueryServiceClient, "rest"), + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, "grpc"), + (transports.SampleQueryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test_sample_query_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", + [ + (SampleQueryServiceClient, "grpc"), + (SampleQueryServiceAsyncClient, "grpc_asyncio"), + (SampleQueryServiceClient, "rest"), + ], +) +def test_sample_query_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_sample_query_service_client_get_transport_class(): + transport = SampleQueryServiceClient.get_transport_class() + available_transports = [ + transports.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceRestTransport, + ] + assert transport in available_transports + + transport = SampleQueryServiceClient.get_transport_class("grpc") + assert transport == transports.SampleQueryServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test_sample_query_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(SampleQueryServiceClient, "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(SampleQueryServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + "true", + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + "false", + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + "true", + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sample_query_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQueryServiceClient, SampleQueryServiceAsyncClient] +) +@mock.patch.object( + SampleQueryServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQueryServiceAsyncClient), +) +def test_sample_query_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQueryServiceClient, SampleQueryServiceAsyncClient] +) +@mock.patch.object( + SampleQueryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceClient), +) +@mock.patch.object( + SampleQueryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQueryServiceAsyncClient), +) +def test_sample_query_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SampleQueryServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQueryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport, "grpc"), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SampleQueryServiceClient, transports.SampleQueryServiceRestTransport, "rest"), + ], +) +def test_sample_query_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SampleQueryServiceClient, + transports.SampleQueryServiceRestTransport, + "rest", + None, + ), + ], +) +def test_sample_query_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_sample_query_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.sample_query_service.transports.SampleQueryServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SampleQueryServiceClient( + 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", + [ + ( + SampleQueryServiceClient, + transports.SampleQueryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sample_query_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + sample_query_service.GetSampleQueryRequest, + dict, + ], +) +def test_get_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery( + name="name_value", + ) + response = client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.GetSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_get_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest() + + +def test_get_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.GetSampleQueryRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest( + name="name_value", + ) + + +def test_get_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sample_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query + ] = mock_rpc + request = {} + client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.get_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.GetSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_get_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_sample_query + ] = mock_object + + request = {} + await client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.GetSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.GetSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_sample_query_async_from_dict(): + await test_get_sample_query_async(request_type=dict) + + +def test_get_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.GetSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value = sample_query.SampleQuery() + client.get_sample_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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.GetSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery() + ) + await client.get_sample_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", + "name=name_value", + ) in kw["metadata"] + + +def test_get_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sample_query( + 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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sample_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sample_query( + 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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.ListSampleQueriesRequest, + dict, + ], +) +def test_list_sample_queries(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.ListSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_queries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceClient( + credentials=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_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest() + + +def test_list_sample_queries_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.ListSampleQueriesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_queries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_sample_queries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_queries in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_queries + ] = mock_rpc + request = {} + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_queries_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.ListSampleQueriesRequest() + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_sample_queries + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_sample_queries + ] = mock_object + + request = {} + await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_queries_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.ListSampleQueriesRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.ListSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_from_dict(): + await test_list_sample_queries_async(request_type=dict) + + +def test_list_sample_queries_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.ListSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value = sample_query_service.ListSampleQueriesResponse() + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.ListSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse() + ) + await client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sample_queries( + 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_sample_queries_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sample_queries_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_service.ListSampleQueriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_service.ListSampleQueriesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sample_queries( + 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_sample_queries_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +def test_list_sample_queries_pager(transport_name: str = "grpc"): + client = SampleQueryServiceClient( + 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_sample_queries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sample_queries(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query.SampleQuery) for i in results) + + +def test_list_sample_queries_pages(transport_name: str = "grpc"): + client = SampleQueryServiceClient( + 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_sample_queries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sample_queries(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_sample_queries_async_pager(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sample_queries( + 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, sample_query.SampleQuery) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sample_queries_async_pages(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_queries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + 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_sample_queries(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", + [ + sample_query_service.CreateSampleQueryRequest, + dict, + ], +) +def test_create_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery( + name="name_value", + ) + response = client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.CreateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_create_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest() + + +def test_create_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.CreateSampleQueryRequest( + parent="parent_value", + sample_query_id="sample_query_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest( + parent="parent_value", + sample_query_id="sample_query_id_value", + ) + + +def test_create_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query + ] = mock_rpc + request = {} + client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.create_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.CreateSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_create_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_sample_query + ] = mock_object + + request = {} + await client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.CreateSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.CreateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_sample_query_async_from_dict(): + await test_create_sample_query_async(request_type=dict) + + +def test_create_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.CreateSampleQueryRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value = gcd_sample_query.SampleQuery() + client.create_sample_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", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.CreateSampleQueryRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + await client.create_sample_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", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sample_query( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ) + assert arg == mock_val + arg = args[0].sample_query_id + mock_val = "sample_query_id_value" + assert arg == mock_val + + +def test_create_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sample_query( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ) + assert arg == mock_val + arg = args[0].sample_query_id + mock_val = "sample_query_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.UpdateSampleQueryRequest, + dict, + ], +) +def test_update_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery( + name="name_value", + ) + response = client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.UpdateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_update_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +def test_update_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.UpdateSampleQueryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +def test_update_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query + ] = mock_rpc + request = {} + client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.update_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.UpdateSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_update_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_sample_query + ] = mock_object + + request = {} + await client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.UpdateSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery( + name="name_value", + ) + ) + response = await client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.UpdateSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_sample_query_async_from_dict(): + await test_update_sample_query_async(request_type=dict) + + +def test_update_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.UpdateSampleQueryRequest() + + request.sample_query.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value = gcd_sample_query.SampleQuery() + client.update_sample_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", + "sample_query.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.UpdateSampleQueryRequest() + + request.sample_query.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + await client.update_sample_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", + "sample_query.name=name_value", + ) in kw["metadata"] + + +def test_update_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sample_query( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query.SampleQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query.SampleQuery() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sample_query( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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].sample_query + mock_val = gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.DeleteSampleQueryRequest, + dict, + ], +) +def test_delete_sample_query(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_service.DeleteSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_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 = SampleQueryServiceClient( + credentials=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_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest() + + +def test_delete_sample_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_service.DeleteSampleQueryRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest( + name="name_value", + ) + + +def test_delete_sample_query_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query + ] = mock_rpc + request = {} + client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_service.DeleteSampleQueryRequest() + + +@pytest.mark.asyncio +async def test_delete_sample_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_sample_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_sample_query + ] = mock_object + + request = {} + await client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_async( + transport: str = "grpc_asyncio", + request_type=sample_query_service.DeleteSampleQueryRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_service.DeleteSampleQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_sample_query_async_from_dict(): + await test_delete_sample_query_async(request_type=dict) + + +def test_delete_sample_query_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.DeleteSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value = None + client.delete_sample_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", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_sample_query_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_service.DeleteSampleQueryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sample_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", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_sample_query_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__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_sample_query( + 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_sample_query_flattened_error(): + client = SampleQueryServiceClient( + credentials=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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sample_query_flattened_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query), "__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_sample_query( + 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_sample_query_flattened_error_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportSampleQueriesRequest, + dict, + ], +) +def test_import_sample_queries(request_type, transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = import_config.ImportSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_sample_queries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceClient( + credentials=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_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest() + + +def test_import_sample_queries_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = import_config.ImportSampleQueriesRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_sample_queries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest( + parent="parent_value", + ) + + +def test_import_sample_queries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_sample_queries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_sample_queries + ] = mock_rpc + request = {} + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_sample_queries_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__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_sample_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportSampleQueriesRequest() + + +@pytest.mark.asyncio +async def test_import_sample_queries_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_sample_queries + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.import_sample_queries + ] = mock_object + + request = {} + await client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_sample_queries_async( + transport: str = "grpc_asyncio", + request_type=import_config.ImportSampleQueriesRequest, +): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_queries), "__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_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = import_config.ImportSampleQueriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_sample_queries_async_from_dict(): + await test_import_sample_queries_async(request_type=dict) + + +def test_import_sample_queries_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_queries_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ImportSampleQueriesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_sample_queries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", + [ + sample_query_service.GetSampleQueryRequest, + dict, + ], +) +def test_get_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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 = sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_get_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sample_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query + ] = mock_rpc + + request = {} + client.get_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_sample_query_rest_required_fields( + request_type=sample_query_service.GetSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_sample_query._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_sample_query._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_get_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_get_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.GetSampleQueryRequest.pb( + sample_query_service.GetSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = sample_query.SampleQuery.to_json( + sample_query.SampleQuery() + ) + + request = sample_query_service.GetSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query.SampleQuery() + + client.get_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.GetSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_get_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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 = sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_get_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.GetSampleQueryRequest(), + name="name_value", + ) + + +def test_get_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.ListSampleQueriesRequest, + dict, + ], +) +def test_list_sample_queries_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_service.ListSampleQueriesResponse( + 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 = sample_query_service.ListSampleQueriesResponse.pb(return_value) + 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_sample_queries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQueriesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_queries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_queries in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_queries + ] = mock_rpc + + request = {} + client.list_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_sample_queries_rest_required_fields( + request_type=sample_query_service.ListSampleQueriesRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sample_queries._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_sample_queries._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_service.ListSampleQueriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_service.ListSampleQueriesResponse.pb( + return_value + ) + 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_sample_queries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sample_queries_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sample_queries._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sample_queries_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_list_sample_queries" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_list_sample_queries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.ListSampleQueriesRequest.pb( + sample_query_service.ListSampleQueriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + sample_query_service.ListSampleQueriesResponse.to_json( + sample_query_service.ListSampleQueriesResponse() + ) + ) + + request = sample_query_service.ListSampleQueriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_service.ListSampleQueriesResponse() + + client.list_sample_queries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sample_queries_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.ListSampleQueriesRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + +def test_list_sample_queries_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_service.ListSampleQueriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_service.ListSampleQueriesResponse.pb(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_sample_queries(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}/sampleQueries" + % client.transport._host, + args[1], + ) + + +def test_list_sample_queries_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_queries( + sample_query_service.ListSampleQueriesRequest(), + parent="parent_value", + ) + + +def test_list_sample_queries_rest_pager(transport: str = "rest"): + client = SampleQueryServiceClient( + 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 = ( + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + next_page_token="abc", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[], + next_page_token="def", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + ], + next_page_token="ghi", + ), + sample_query_service.ListSampleQueriesResponse( + sample_queries=[ + sample_query.SampleQuery(), + sample_query.SampleQuery(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + sample_query_service.ListSampleQueriesResponse.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/sampleQuerySets/sample3" + } + + pager = client.list_sample_queries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query.SampleQuery) for i in results) + + pages = list(client.list_sample_queries(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", + [ + sample_query_service.CreateSampleQueryRequest, + dict, + ], +) +def test_create_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + request_init["sample_query"] = { + "query_entry": { + "query": "query_value", + "targets": [ + {"uri": "uri_value", "page_numbers": [1273, 1274], "score": 0.54} + ], + }, + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_service.CreateSampleQueryRequest.meta.fields[ + "sample_query" + ] + + 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["sample_query"].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["sample_query"][field])): + del request_init["sample_query"][field][i][subfield] + else: + del request_init["sample_query"][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_sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_create_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query + ] = mock_rpc + + request = {} + client.create_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_sample_query_rest_required_fields( + request_type=sample_query_service.CreateSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sample_query_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "sampleQueryId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sampleQueryId" in jsonified_request + assert jsonified_request["sampleQueryId"] == request_init["sample_query_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sampleQueryId"] = "sample_query_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("sample_query_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 "sampleQueryId" in jsonified_request + assert jsonified_request["sampleQueryId"] == "sample_query_id_value" + + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [ + ( + "sampleQueryId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("sampleQueryId",)) + & set( + ( + "parent", + "sampleQuery", + "sampleQueryId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_create_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_create_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.CreateSampleQueryRequest.pb( + sample_query_service.CreateSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query.SampleQuery.to_json( + gcd_sample_query.SampleQuery() + ) + + request = sample_query_service.CreateSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query.SampleQuery() + + client.create_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.CreateSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query(request) + + +def test_create_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_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_sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}/sampleQueries" + % client.transport._host, + args[1], + ) + + +def test_create_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.CreateSampleQueryRequest(), + parent="parent_value", + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + sample_query_id="sample_query_id_value", + ) + + +def test_create_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.UpdateSampleQueryRequest, + dict, + ], +) +def test_update_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4" + } + } + request_init["sample_query"] = { + "query_entry": { + "query": "query_value", + "targets": [ + {"uri": "uri_value", "page_numbers": [1273, 1274], "score": 0.54} + ], + }, + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4", + "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 = sample_query_service.UpdateSampleQueryRequest.meta.fields[ + "sample_query" + ] + + 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["sample_query"].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["sample_query"][field])): + del request_init["sample_query"][field][i][subfield] + else: + del request_init["sample_query"][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_sample_query.SampleQuery( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query.SampleQuery) + assert response.name == "name_value" + + +def test_update_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query + ] = mock_rpc + + request = {} + client.update_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_sample_query_rest_required_fields( + request_type=sample_query_service.UpdateSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_sample_query._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_sample_query._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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query.SampleQuery() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query.SampleQuery.pb(return_value) + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("sampleQuery",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "post_update_sample_query" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_update_sample_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_service.UpdateSampleQueryRequest.pb( + sample_query_service.UpdateSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query.SampleQuery.to_json( + gcd_sample_query.SampleQuery() + ) + + request = sample_query_service.UpdateSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query.SampleQuery() + + client.update_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.UpdateSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_update_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query.SampleQuery() + + # get arguments that satisfy an http rule for this method + sample_request = { + "sample_query": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_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_sample_query.SampleQuery.pb(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_sample_query(**mock_args) + + # Establish that the underlying call 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/{sample_query.name=projects/*/locations/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_update_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.UpdateSampleQueryRequest(), + sample_query=gcd_sample_query.SampleQuery( + query_entry=gcd_sample_query.SampleQuery.QueryEntry(query="query_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_service.DeleteSampleQueryRequest, + dict, + ], +) +def test_delete_sample_query_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query + ] = mock_rpc + + request = {} + client.delete_sample_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_sample_query_rest_required_fields( + request_type=sample_query_service.DeleteSampleQueryRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sample_query._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_sample_query._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 = SampleQueryServiceClient( + 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_sample_query(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_sample_query_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sample_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sample_query_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_delete_sample_query" + ) as pre: + pre.assert_not_called() + pb_message = sample_query_service.DeleteSampleQueryRequest.pb( + sample_query_service.DeleteSampleQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "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 = sample_query_service.DeleteSampleQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sample_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_sample_query_rest_bad_request( + transport: str = "rest", request_type=sample_query_service.DeleteSampleQueryRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3/sampleQueries/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_sample_query(request) + + +def test_delete_sample_query_rest_flattened(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/sampleQuerySets/sample3/sampleQueries/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_sample_query(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*/sampleQueries/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_sample_query_rest_flattened_error(transport: str = "rest"): + client = SampleQueryServiceClient( + credentials=ga_credentials.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_sample_query( + sample_query_service.DeleteSampleQueryRequest(), + name="name_value", + ) + + +def test_delete_sample_query_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportSampleQueriesRequest, + dict, + ], +) +def test_import_sample_queries_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_sample_queries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_sample_queries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_sample_queries + ] = mock_rpc + + request = {} + client.import_sample_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_sample_queries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_sample_queries_rest_required_fields( + request_type=import_config.ImportSampleQueriesRequest, +): + transport_class = transports.SampleQueryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_sample_queries._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_sample_queries._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 = SampleQueryServiceClient( + 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_sample_queries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_sample_queries_rest_unset_required_fields(): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_sample_queries._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_sample_queries_rest_interceptors(null_interceptor): + transport = transports.SampleQueryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQueryServiceRestInterceptor(), + ) + client = SampleQueryServiceClient(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.SampleQueryServiceRestInterceptor, "post_import_sample_queries" + ) as post, mock.patch.object( + transports.SampleQueryServiceRestInterceptor, "pre_import_sample_queries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportSampleQueriesRequest.pb( + import_config.ImportSampleQueriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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.ImportSampleQueriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_sample_queries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_sample_queries_rest_bad_request( + transport: str = "rest", request_type=import_config.ImportSampleQueriesRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_queries(request) + + +def test_import_sample_queries_rest_error(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQueryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SampleQueryServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQueryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SampleQueryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + transports.SampleQueryServiceRestTransport, + ], +) +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 = SampleQueryServiceClient.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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SampleQueryServiceGrpcTransport, + ) + + +def test_sample_query_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SampleQueryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sample_query_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.sample_query_service.transports.SampleQueryServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SampleQueryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_sample_query", + "list_sample_queries", + "create_sample_query", + "update_sample_query", + "delete_sample_query", + "import_sample_queries", + "get_operation", + "cancel_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_sample_query_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.sample_query_service.transports.SampleQueryServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQueryServiceTransport( + 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_sample_query_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.sample_query_service.transports.SampleQueryServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQueryServiceTransport() + adc.assert_called_once() + + +def test_sample_query_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) + SampleQueryServiceClient() + 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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + transports.SampleQueryServiceRestTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, grpc_helpers), + (transports.SampleQueryServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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_sample_query_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.SampleQueryServiceRestTransport( + 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_sample_query_service_rest_lro_client(): + client = SampleQueryServiceClient( + 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_sample_query_service_host_no_port(transport_name): + client = SampleQueryServiceClient( + 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_sample_query_service_host_with_port(transport_name): + client = SampleQueryServiceClient( + 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_sample_query_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SampleQueryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SampleQueryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_sample_query._session + session2 = client2.transport.get_sample_query._session + assert session1 != session2 + session1 = client1.transport.list_sample_queries._session + session2 = client2.transport.list_sample_queries._session + assert session1 != session2 + session1 = client1.transport.create_sample_query._session + session2 = client2.transport.create_sample_query._session + assert session1 != session2 + session1 = client1.transport.update_sample_query._session + session2 = client2.transport.update_sample_query._session + assert session1 != session2 + session1 = client1.transport.delete_sample_query._session + session2 = client2.transport.delete_sample_query._session + assert session1 != session2 + session1 = client1.transport.import_sample_queries._session + session2 = client2.transport.import_sample_queries._session + assert session1 != session2 + + +def test_sample_query_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQueryServiceGrpcTransport( + 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_sample_query_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQueryServiceGrpcAsyncIOTransport( + 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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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.SampleQueryServiceGrpcTransport, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_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_sample_query_service_grpc_lro_client(): + client = SampleQueryServiceClient( + 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_sample_query_service_grpc_lro_async_client(): + client = SampleQueryServiceAsyncClient( + 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_sample_query_path(): + project = "squid" + location = "clam" + sample_query_set = "whelk" + sample_query = "octopus" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}/sampleQueries/{sample_query}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + sample_query=sample_query, + ) + actual = SampleQueryServiceClient.sample_query_path( + project, location, sample_query_set, sample_query + ) + assert expected == actual + + +def test_parse_sample_query_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "sample_query_set": "cuttlefish", + "sample_query": "mussel", + } + path = SampleQueryServiceClient.sample_query_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_sample_query_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "winkle" + location = "nautilus" + sample_query_set = "scallop" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = SampleQueryServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "abalone", + "location": "squid", + "sample_query_set": "clam", + } + path = SampleQueryServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SampleQueryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SampleQueryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SampleQueryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SampleQueryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SampleQueryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SampleQueryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = SampleQueryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SampleQueryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.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 = SampleQueryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SampleQueryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQueryServiceClient.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.SampleQueryServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SampleQueryServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SampleQueryServiceClient.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 = SampleQueryServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SampleQueryServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SampleQueryServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceAsyncClient( + 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQueryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceAsyncClient( + 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 = SampleQueryServiceClient( + 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 = SampleQueryServiceClient( + 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", + [ + (SampleQueryServiceClient, transports.SampleQueryServiceGrpcTransport), + ( + SampleQueryServiceAsyncClient, + transports.SampleQueryServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_set_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_set_service.py new file mode 100644 index 000000000000..4ff1019b5439 --- /dev/null +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_sample_query_set_service.py @@ -0,0 +1,6631 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +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_v1beta.services.sample_query_set_service import ( + SampleQuerySetServiceAsyncClient, + SampleQuerySetServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1beta.types import ( + sample_query_set as gcd_sample_query_set, +) +from google.cloud.discoveryengine_v1beta.types import sample_query_set +from google.cloud.discoveryengine_v1beta.types import sample_query_set_service + + +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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SampleQuerySetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + SampleQuerySetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQuerySetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SampleQuerySetServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SampleQuerySetServiceClient._get_client_cert_source(None, False) is None + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SampleQuerySetServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SampleQuerySetServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SampleQuerySetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + SampleQuerySetServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SampleQuerySetServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SampleQuerySetServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SampleQuerySetServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SampleQuerySetServiceClient._get_universe_domain(None, None) + == SampleQuerySetServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SampleQuerySetServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SampleQuerySetServiceClient, "grpc"), + (SampleQuerySetServiceAsyncClient, "grpc_asyncio"), + (SampleQuerySetServiceClient, "rest"), + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, "grpc"), + (transports.SampleQuerySetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SampleQuerySetServiceRestTransport, "rest"), + ], +) +def test_sample_query_set_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", + [ + (SampleQuerySetServiceClient, "grpc"), + (SampleQuerySetServiceAsyncClient, "grpc_asyncio"), + (SampleQuerySetServiceClient, "rest"), + ], +) +def test_sample_query_set_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_sample_query_set_service_client_get_transport_class(): + transport = SampleQuerySetServiceClient.get_transport_class() + available_transports = [ + transports.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceRestTransport, + ] + assert transport in available_transports + + transport = SampleQuerySetServiceClient.get_transport_class("grpc") + assert transport == transports.SampleQuerySetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_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(SampleQuerySetServiceClient, "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(SampleQuerySetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + "true", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + "false", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + "true", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sample_query_set_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQuerySetServiceClient, SampleQuerySetServiceAsyncClient] +) +@mock.patch.object( + SampleQuerySetServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [SampleQuerySetServiceClient, SampleQuerySetServiceAsyncClient] +) +@mock.patch.object( + SampleQuerySetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceClient), +) +@mock.patch.object( + SampleQuerySetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SampleQuerySetServiceAsyncClient), +) +def test_sample_query_set_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SampleQuerySetServiceClient._DEFAULT_UNIVERSE + default_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SampleQuerySetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + ), + ], +) +def test_sample_query_set_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceRestTransport, + "rest", + None, + ), + ], +) +def test_sample_query_set_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_sample_query_set_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.transports.SampleQuerySetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SampleQuerySetServiceClient( + 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", + [ + ( + SampleQuerySetServiceClient, + transports.SampleQuerySetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sample_query_set_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "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", + [ + sample_query_set_service.GetSampleQuerySetRequest, + dict, + ], +) +def test_get_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.GetSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest() + + +def test_get_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.GetSampleQuerySetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest( + name="name_value", + ) + + +def test_get_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_sample_query_set in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query_set + ] = mock_rpc + request = {} + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.GetSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_sample_query_set + ] = mock_object + + request = {} + await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.GetSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_get_sample_query_set_async_from_dict(): + await test_get_sample_query_set_async(request_type=dict) + + +def test_get_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.GetSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value = sample_query_set.SampleQuerySet() + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.GetSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet() + ) + await client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sample_query_set( + 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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sample_query_set( + 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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.ListSampleQuerySetsRequest, + dict, + ], +) +def test_list_sample_query_sets(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.ListSampleQuerySetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_query_sets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_sets), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_query_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest() + + +def test_list_sample_query_sets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.ListSampleQuerySetsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sample_query_sets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_sample_query_sets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_query_sets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_query_sets + ] = mock_rpc + request = {} + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_query_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.ListSampleQuerySetsRequest() + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_sample_query_sets + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_sample_query_sets + ] = mock_object + + request = {} + await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.ListSampleQuerySetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_from_dict(): + await test_list_sample_query_sets_async(request_type=dict) + + +def test_list_sample_query_sets_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.ListSampleQuerySetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_sets_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.ListSampleQuerySetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + await client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_sets_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sample_query_sets( + 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_sample_query_sets_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sample_query_sets( + 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_sample_query_sets_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +def test_list_sample_query_sets_pager(transport_name: str = "grpc"): + client = SampleQuerySetServiceClient( + 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_sample_query_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sample_query_sets(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query_set.SampleQuerySet) for i in results) + + +def test_list_sample_query_sets_pages(transport_name: str = "grpc"): + client = SampleQuerySetServiceClient( + 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_sample_query_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sample_query_sets(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_sample_query_sets_async_pager(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sample_query_sets( + 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, sample_query_set.SampleQuerySet) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sample_query_sets_async_pages(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sample_query_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + 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_sample_query_sets(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", + [ + sample_query_set_service.CreateSampleQuerySetRequest, + dict, + ], +) +def test_create_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.CreateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest() + + +def test_create_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set_id="sample_query_set_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest( + parent="parent_value", + sample_query_set_id="sample_query_set_id_value", + ) + + +def test_create_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query_set + ] = mock_rpc + request = {} + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.CreateSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_sample_query_set + ] = mock_object + + request = {} + await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.CreateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_create_sample_query_set_async_from_dict(): + await test_create_sample_query_set_async(request_type=dict) + + +def test_create_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.CreateSampleQuerySetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value = gcd_sample_query_set.SampleQuerySet() + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.CreateSampleQuerySetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + await client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sample_query_set( + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(name="name_value") + assert arg == mock_val + arg = args[0].sample_query_set_id + mock_val = "sample_query_set_id_value" + assert arg == mock_val + + +def test_create_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sample_query_set( + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(name="name_value") + assert arg == mock_val + arg = args[0].sample_query_set_id + mock_val = "sample_query_set_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.UpdateSampleQuerySetRequest, + dict, + ], +) +def test_update_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.UpdateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +def test_update_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +def test_update_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query_set + ] = mock_rpc + request = {} + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.UpdateSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_sample_query_set + ] = mock_object + + request = {} + await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.UpdateSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_update_sample_query_set_async_from_dict(): + await test_update_sample_query_set_async(request_type=dict) + + +def test_update_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + request.sample_query_set.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value = gcd_sample_query_set.SampleQuerySet() + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "sample_query_set.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.UpdateSampleQuerySetRequest() + + request.sample_query_set.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + await client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "sample_query_set.name=name_value", + ) in kw["metadata"] + + +def test_update_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sample_query_set( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sample_query_set.SampleQuerySet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sample_query_set.SampleQuerySet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sample_query_set( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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].sample_query_set + mock_val = gcd_sample_query_set.SampleQuerySet(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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.DeleteSampleQuerySetRequest, + dict, + ], +) +def test_delete_sample_query_set(request_type, transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.DeleteSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest() + + +def test_delete_sample_query_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = sample_query_set_service.DeleteSampleQuerySetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sample_query_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest( + name="name_value", + ) + + +def test_delete_sample_query_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query_set + ] = mock_rpc + request = {} + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sample_query_set_service.DeleteSampleQuerySetRequest() + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_sample_query_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_sample_query_set + ] = mock_object + + request = {} + await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async( + transport: str = "grpc_asyncio", + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sample_query_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sample_query_set_service.DeleteSampleQuerySetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_async_from_dict(): + await test_delete_sample_query_set_async(request_type=dict) + + +def test_delete_sample_query_set_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.DeleteSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value = None + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = sample_query_set_service.DeleteSampleQuerySetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_sample_query_set_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__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_sample_query_set( + 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_sample_query_set_flattened_error(): + client = SampleQuerySetServiceClient( + credentials=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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sample_query_set_flattened_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sample_query_set), "__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_sample_query_set( + 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_sample_query_set_flattened_error_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.GetSampleQuerySetRequest, + dict, + ], +) +def test_get_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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 = sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_sample_query_set in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_sample_query_set + ] = mock_rpc + + request = {} + client.get_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_get_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_get_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.GetSampleQuerySetRequest.pb( + sample_query_set_service.GetSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = sample_query_set.SampleQuerySet.to_json( + sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.GetSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_set.SampleQuerySet() + + client.get_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.GetSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_get_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_set.SampleQuerySet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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 = sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_get_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.GetSampleQuerySetRequest(), + name="name_value", + ) + + +def test_get_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.ListSampleQuerySetsRequest, + dict, + ], +) +def test_list_sample_query_sets_rest(request_type): + client = SampleQuerySetServiceClient( + 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 = sample_query_set_service.ListSampleQuerySetsResponse( + 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + return_value + ) + 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_sample_query_sets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSampleQuerySetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sample_query_sets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_sample_query_sets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_sample_query_sets + ] = mock_rpc + + request = {} + client.list_sample_query_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sample_query_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_sample_query_sets_rest_required_fields( + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sample_query_sets._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_sample_query_sets._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sample_query_set_service.ListSampleQuerySetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + return_value + ) + 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_sample_query_sets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sample_query_sets_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sample_query_sets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sample_query_sets_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_list_sample_query_sets" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_list_sample_query_sets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.ListSampleQuerySetsRequest.pb( + sample_query_set_service.ListSampleQuerySetsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + sample_query_set_service.ListSampleQuerySetsResponse.to_json( + sample_query_set_service.ListSampleQuerySetsResponse() + ) + ) + + request = sample_query_set_service.ListSampleQuerySetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + client.list_sample_query_sets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sample_query_sets_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.ListSampleQuerySetsRequest, +): + client = SampleQuerySetServiceClient( + 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_sample_query_sets(request) + + +def test_list_sample_query_sets_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = sample_query_set_service.ListSampleQuerySetsResponse() + + # 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 = sample_query_set_service.ListSampleQuerySetsResponse.pb( + 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_sample_query_sets(**mock_args) + + # Establish that the underlying call 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/*}/sampleQuerySets" + % client.transport._host, + args[1], + ) + + +def test_list_sample_query_sets_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_sets( + sample_query_set_service.ListSampleQuerySetsRequest(), + parent="parent_value", + ) + + +def test_list_sample_query_sets_rest_pager(transport: str = "rest"): + client = SampleQuerySetServiceClient( + 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 = ( + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + next_page_token="abc", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[], + next_page_token="def", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + ], + next_page_token="ghi", + ), + sample_query_set_service.ListSampleQuerySetsResponse( + sample_query_sets=[ + sample_query_set.SampleQuerySet(), + sample_query_set.SampleQuerySet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + sample_query_set_service.ListSampleQuerySetsResponse.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_sample_query_sets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sample_query_set.SampleQuerySet) for i in results) + + pages = list(client.list_sample_query_sets(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", + [ + sample_query_set_service.CreateSampleQuerySetRequest, + dict, + ], +) +def test_create_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["sample_query_set"] = { + "name": "name_value", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_set_service.CreateSampleQuerySetRequest.meta.fields[ + "sample_query_set" + ] + + 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["sample_query_set"].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["sample_query_set"][field])): + del request_init["sample_query_set"][field][i][subfield] + else: + del request_init["sample_query_set"][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_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_sample_query_set + ] = mock_rpc + + request = {} + client.create_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sample_query_set_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "sampleQuerySetId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sampleQuerySetId" in jsonified_request + assert jsonified_request["sampleQuerySetId"] == request_init["sample_query_set_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sampleQuerySetId"] = "sample_query_set_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sample_query_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("sample_query_set_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 "sampleQuerySetId" in jsonified_request + assert jsonified_request["sampleQuerySetId"] == "sample_query_set_id_value" + + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [ + ( + "sampleQuerySetId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("sampleQuerySetId",)) + & set( + ( + "parent", + "sampleQuerySet", + "sampleQuerySetId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_create_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_create_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.CreateSampleQuerySetRequest.pb( + sample_query_set_service.CreateSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query_set.SampleQuerySet.to_json( + gcd_sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.CreateSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query_set.SampleQuerySet() + + client.create_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.CreateSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + 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_sample_query_set(request) + + +def test_create_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query_set.SampleQuerySet() + + # 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", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_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_sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*}/sampleQuerySets" + % client.transport._host, + args[1], + ) + + +def test_create_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.CreateSampleQuerySetRequest(), + parent="parent_value", + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + sample_query_set_id="sample_query_set_id_value", + ) + + +def test_create_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.UpdateSampleQuerySetRequest, + dict, + ], +) +def test_update_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + } + request_init["sample_query_set"] = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sample_query_set_service.UpdateSampleQuerySetRequest.meta.fields[ + "sample_query_set" + ] + + 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["sample_query_set"].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["sample_query_set"][field])): + del request_init["sample_query_set"][field][i][subfield] + else: + del request_init["sample_query_set"][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_sample_query_set.SampleQuerySet( + name="name_value", + display_name="display_name_value", + description="description_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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sample_query_set.SampleQuerySet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_sample_query_set + ] = mock_rpc + + request = {} + client.update_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sample_query_set.SampleQuerySet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_sample_query_set.SampleQuerySet.pb(return_value) + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("sampleQuerySet",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "post_update_sample_query_set" + ) as post, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_update_sample_query_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = sample_query_set_service.UpdateSampleQuerySetRequest.pb( + sample_query_set_service.UpdateSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_sample_query_set.SampleQuerySet.to_json( + gcd_sample_query_set.SampleQuerySet() + ) + + request = sample_query_set_service.UpdateSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sample_query_set.SampleQuerySet() + + client.update_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.UpdateSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_update_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_sample_query_set.SampleQuerySet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "sample_query_set": { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + sample_query_set=gcd_sample_query_set.SampleQuerySet(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_sample_query_set.SampleQuerySet.pb(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_sample_query_set(**mock_args) + + # Establish that the underlying call 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/{sample_query_set.name=projects/*/locations/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.UpdateSampleQuerySetRequest(), + sample_query_set=gcd_sample_query_set.SampleQuerySet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sample_query_set_service.DeleteSampleQuerySetRequest, + dict, + ], +) +def test_delete_sample_query_set_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_sample_query_set(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sample_query_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_sample_query_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_sample_query_set + ] = mock_rpc + + request = {} + client.delete_sample_query_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sample_query_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_sample_query_set_rest_required_fields( + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + transport_class = transports.SampleQuerySetServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sample_query_set._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_sample_query_set._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 = SampleQuerySetServiceClient( + 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_sample_query_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_sample_query_set_rest_unset_required_fields(): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sample_query_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sample_query_set_rest_interceptors(null_interceptor): + transport = transports.SampleQuerySetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SampleQuerySetServiceRestInterceptor(), + ) + client = SampleQuerySetServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SampleQuerySetServiceRestInterceptor, "pre_delete_sample_query_set" + ) as pre: + pre.assert_not_called() + pb_message = sample_query_set_service.DeleteSampleQuerySetRequest.pb( + sample_query_set_service.DeleteSampleQuerySetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "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 = sample_query_set_service.DeleteSampleQuerySetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sample_query_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_sample_query_set_rest_bad_request( + transport: str = "rest", + request_type=sample_query_set_service.DeleteSampleQuerySetRequest, +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sampleQuerySets/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_sample_query_set(request) + + +def test_delete_sample_query_set_rest_flattened(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/sampleQuerySets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_sample_query_set(**mock_args) + + # Establish that the underlying call 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/*/sampleQuerySets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_sample_query_set_rest_flattened_error(transport: str = "rest"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.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_sample_query_set( + sample_query_set_service.DeleteSampleQuerySetRequest(), + name="name_value", + ) + + +def test_delete_sample_query_set_rest_error(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SampleQuerySetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SampleQuerySetServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SampleQuerySetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SampleQuerySetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + transports.SampleQuerySetServiceRestTransport, + ], +) +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 = SampleQuerySetServiceClient.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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SampleQuerySetServiceGrpcTransport, + ) + + +def test_sample_query_set_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SampleQuerySetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sample_query_set_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.transports.SampleQuerySetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SampleQuerySetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_sample_query_set", + "list_sample_query_sets", + "create_sample_query_set", + "update_sample_query_set", + "delete_sample_query_set", + "get_operation", + "cancel_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_sample_query_set_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.sample_query_set_service.transports.SampleQuerySetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQuerySetServiceTransport( + 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_sample_query_set_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.sample_query_set_service.transports.SampleQuerySetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SampleQuerySetServiceTransport() + adc.assert_called_once() + + +def test_sample_query_set_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) + SampleQuerySetServiceClient() + 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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + transports.SampleQuerySetServiceRestTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, grpc_helpers), + (transports.SampleQuerySetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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_sample_query_set_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.SampleQuerySetServiceRestTransport( + 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_sample_query_set_service_host_no_port(transport_name): + client = SampleQuerySetServiceClient( + 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_sample_query_set_service_host_with_port(transport_name): + client = SampleQuerySetServiceClient( + 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_sample_query_set_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SampleQuerySetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SampleQuerySetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_sample_query_set._session + session2 = client2.transport.get_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.list_sample_query_sets._session + session2 = client2.transport.list_sample_query_sets._session + assert session1 != session2 + session1 = client1.transport.create_sample_query_set._session + session2 = client2.transport.create_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.update_sample_query_set._session + session2 = client2.transport.update_sample_query_set._session + assert session1 != session2 + session1 = client1.transport.delete_sample_query_set._session + session2 = client2.transport.delete_sample_query_set._session + assert session1 != session2 + + +def test_sample_query_set_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQuerySetServiceGrpcTransport( + 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_sample_query_set_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SampleQuerySetServiceGrpcAsyncIOTransport( + 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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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.SampleQuerySetServiceGrpcTransport, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ], +) +def test_sample_query_set_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_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SampleQuerySetServiceClient.location_path(project, location) + assert expected == actual + + +def test_parse_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SampleQuerySetServiceClient.location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_location_path(path) + assert expected == actual + + +def test_sample_query_set_path(): + project = "oyster" + location = "nudibranch" + sample_query_set = "cuttlefish" + expected = "projects/{project}/locations/{location}/sampleQuerySets/{sample_query_set}".format( + project=project, + location=location, + sample_query_set=sample_query_set, + ) + actual = SampleQuerySetServiceClient.sample_query_set_path( + project, location, sample_query_set + ) + assert expected == actual + + +def test_parse_sample_query_set_path(): + expected = { + "project": "mussel", + "location": "winkle", + "sample_query_set": "nautilus", + } + path = SampleQuerySetServiceClient.sample_query_set_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_sample_query_set_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SampleQuerySetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = SampleQuerySetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SampleQuerySetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = SampleQuerySetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SampleQuerySetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = SampleQuerySetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = SampleQuerySetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = SampleQuerySetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SampleQuerySetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = SampleQuerySetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SampleQuerySetServiceClient.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.SampleQuerySetServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SampleQuerySetServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SampleQuerySetServiceClient.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 = SampleQuerySetServiceAsyncClient( + 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_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SampleQuerySetServiceClient( + 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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SampleQuerySetServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector/operations/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() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + }, + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a 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_cancel_operation(transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceAsyncClient( + 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = SampleQuerySetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceAsyncClient( + 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 = SampleQuerySetServiceClient( + 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 = SampleQuerySetServiceClient( + 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", + [ + (SampleQuerySetServiceClient, transports.SampleQuerySetServiceGrpcTransport), + ( + SampleQuerySetServiceAsyncClient, + transports.SampleQuerySetServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py index 717c71cf715b..c84acc6abc57 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py @@ -2503,6 +2503,43 @@ def test_parse_branch_path(): assert expected == actual +def test_chunk_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + chunk = "clam" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}/chunks/{chunk}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + chunk=chunk, + ) + actual = SearchServiceClient.chunk_path( + project, location, data_store, branch, document, chunk + ) + assert expected == actual + + +def test_parse_chunk_path(): + expected = { + "project": "whelk", + "location": "octopus", + "data_store": "oyster", + "branch": "nudibranch", + "document": "cuttlefish", + "chunk": "mussel", + } + path = SearchServiceClient.chunk_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_chunk_path(path) + assert expected == actual + + def test_data_store_path(): project = "winkle" location = "nautilus" diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py index 358e502515db..a965773e9952 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py @@ -2765,6 +2765,8 @@ def test_update_serving_config_rest(request_type): "num_previous_segments": 2289, "num_next_segments": 1843, }, + "search_result_mode": 1, + "chunk_spec": {"num_previous_chunks": 2071, "num_next_chunks": 1625}, } }, "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4",